skip to Main Content

How in php to replace the key in an array, with the key of a sub-array to get this effect:
from:

`Array
(
    [0] => Array
        (
            [for_a] => me
        )

    [1] => Array
        (
            [for_b] => you
        )

    [2] => Array
        (
            [for_c] => bleeh
        )
)`

to:

`Array
(
    [for_a] => me
    [for_b] => you
    [for_c] => bleeh

)`

I tried with array_column, but it had no effect

3

Answers


  1. You could do it like this:

    This method assumes that there is only one element in each (the hardcoded [0]s in $arr2[array_keys($arr)[0]] = array_values($arr)[0];)

    <?php
    //initialize source array
    $arr1 = array(
        array("for_a"=>"me"),
        array("for_b"=>"you"),
        array("for_c"=>"bleeh")
    );
    
    //initialize output array
    $arr2 = array();
    
    //debug printsource array
    print_r ($arr1);
    
    foreach($arr1 as $arr){
        $arr2[array_keys($arr)[0]] = array_values($arr)[0];
    
    }
    //debug: print output array
    print_r ($arr2);
    
    

    It is not the most elegant way. There is a method called array_walk where you can define a callback function parsing each element of your array, in which you can make sure you don’t overwrite the existing elements of the array.

    Login or Signup to reply.
  2. @Josste gave a good example, and here’s another way you could do it:

    Looping through your array twice, once to grab the parent array and then again for each of the children then use the parent key to update a new array key for the output.

    <?php
    $array = [
        [
            'for_a' => 'me'
        ],
        [
            'for_b' => 'you'
        ],
        [
            'for_c' => 'bleeh'
        ]
    ];
    
    $new = [];
    foreach($array as $arr) {
        foreach($arr as $key => $val) {
            $new[key($arr)] = $val;
        }
    }
    
    echo "<pre>" . print_r($new, TRUE) . "</pre>";
    
    Login or Signup to reply.
  3. Try this php script:

    <?php
    
    $vetor[] = array("for_a" => "me");
    $vetor[] = array("for_b" => "you");
    $vetor[] = array("for_c" => "bleeh");
    
    print_r($vetor);
    
    foreach($vetor as $x)
    {
        foreach($x as $key=>$value) {
            $vetor2[$key] = $value;
        }
    }
    
    print_r($vetor2);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search