1

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?

0

1 Answer 1

4

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.'
)
Sign up to request clarification or add additional context in comments.

1 Comment

Oh my god. You're really awesome. Thank you a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.