0

Beginner question. Initial php array is multidimensional with arrays inside. Take a look.

    Array
    (
[0] => Array
    (
        [textkey] => text
        [file] => file.txt
    )

[1] => Array
    (
        [anotherkey] => another text
        [file] => file2.xml
    )

[2] => Array
    (
        [text_success] => Success
        [newfile] => scope.txt
    ))

How to rebuild it with foreach or other way? Is any function to rebuild array to?

Array
(
[textkey] => text
[file] => file.txt
[anotherkey] => another text
[file] => file2.xml
[text_success] => Success
[newfile] => scope.txt
)
S.M. Pat
  • 308
  • 3
  • 12

2 Answers2

0

This is the code you may want where $array = to the array you specified above.

$newArray = [];

foreach($array as $segment) {
    foreach($segment as $key => $value) {
        $newArray[$key] = $value;
    }
}

print_r($newArray);

This is the output:

Array
(
    [textkey] => text
    [file] => file2.xml
    [anotherkey] => another text
    [text_success] => Success
    [newfile] => scope.txt
)

But, there is a problem. Both the file keys are not shown, because a single key cannot be used multiple times in an array. To get over that issue, you can assign a simple array to the file key with the file names like this:

$newArray = [];

foreach($array as $segment) {
    foreach($segment as $key => $value) {
        if($key == 'file') {
            $newArray['file'][] = $value;   
        } else {
            $newArray[$key] = $value;
        }
    }
}

print_r($newArray);

This gives the output:

Array
(
    [textkey] => text
    [file] => Array
        (
            [0] => file.txt
            [1] => file2.xml
        )

    [anotherkey] => another text
    [text_success] => Success
    [newfile] => scope.txt
)
codez
  • 1,440
  • 2
  • 19
  • 34
-1

There's no premade function for this, but just create a new array to hold the results of iterating over the first level and then pulling the keys and values of the second level with a foreach. There's a couple of ways to do this, but this is usually how I go about it.

$NewArray = array();
for($i = 0; $i <= count($ExistingArray); $i++){
   foreach($ExistingArray[$i] as $key => $val){
        $NewArray[$key] = $val;
   }
}
MichaelClark
  • 1,192
  • 8
  • 7