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
)
2
  • 1
    It's not possible with the 'file' key, since there are two of them. Commented Nov 15, 2015 at 6:01
  • The resulting array that you wrote manually cannot have duplicated key file Commented Nov 15, 2015 at 6:15

2 Answers 2

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

Comments

-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;
   }
}

1 Comment

and yeah, you can't have duplicate keys,..I didn't notice that

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.