x2df2na
x2df2na

Reputation: 55

Convert multidimensional array to a simple array by recursion

How to convert this array:

$array = [
    "order" => [
        "items" => [
            "6" => [
                "ndc" => "This value should not be blank."
            ],
            "7" => [
                "ndc" => "This value should not be blank."
            ]
        ]
    ]
];

to

$array = [
    "order[items][6][ndc]" => "This value should not be blank.",
    "order[items][7][ndc]" => "This value should not be blank.",
];

First array may have unlimited number of nested levels. So nested foreach is not an option.

I spent a lot of time searching for the solution and got nothing. Can, please, someone help or guide me?

Upvotes: 1

Views: 62

Answers (1)

Clément Malet
Clément Malet

Reputation: 5090

Something like this should do the job :

$newArr = [];

function reduce_multi_arr($array, &$newArr, $keys = '') {
  if (!is_array($array)) {
      $newArr[$keys] = $array;
  } else {
      foreach ($array as $key => $val) {
        if ($keys === '') $nextKey = $key; // first key
        else $nextKey = '[' . $key . ']'; // next [keys]
        reduce_multi_arr($val, $newArr, $keys . $nextKey);
      }
  }
}

reduce_multi_arr($array, $newArr);

print_r($newArr);

Output :

Array
(
    [order[items][6][ndc]] => 'This value should not be blank.'
    [order[items][7][ndc]] => 'This value should not be blank.'
)

Upvotes: 4

Related Questions