skip to Main Content

I am trying to match up my array with the manner which the array needs to be sent to another file. I am able to pass the data successfully but as its not in the right structure not getting the desired results I was hoping for.

Currently the variable that my array is within produces this when I do a print_pre

Array
(
  [0] => 788
  [1] => 780
  [2] => 614
)

However I need to get this into the following structure

Array
(
  [0] => Array
    (
      [0] => 788
    )
  [1] => Array
    (
      [0] => 780
    )
  [2] => Array
    (
      [0] => 614
    )
)

I have tried playing around with array_merge, array_column, and a few others but to no avail.

Here is the foreach loop I am building out the array within

$new_array = [];
foreach($old_array as $key => $value) {

    if (empty($key)){
        $new_array = $value;
    }
}

What is the best method to make the array in the structure I desire?

2

Answers


  1. To achieve the desired structure of your array, you need to wrap each individual value of your original array ($old_array) into its own sub-array within $new_array. This can be done by pushing the values into the new array as arrays themselves inside the loop.

    Login or Signup to reply.
  2. basically I want each value to be inside its own array within its own key as outlined in the desired structure.

    So, let’s walk over all array elements, and replace them with themselves wrapped into an additional array "layer":

    $array = [788, 780, 614];
    
    array_walk($array, function(&$elem) { $elem = [$elem]; });
    
    print_r($array);
    

    Result:

    Array
    (
        [0] => Array
            (
                [0] => 788
            )
    
        [1] => Array
            (
                [0] => 780
            )
    
        [2] => Array
            (
                [0] => 614
            )
    
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search