phparraysmultidimensional-arrayarray-pusharray-walk

Push key value in empty array using php


I have associative array and value related with that key contain json_encoded data so I converted it and it resulted in array,I am using array_walk to iterate each array value than and printing values using foreach loop but at same time I want to push (key and values) in empty array which is declared outside but it is not inserting any value.

Note: Here $result is associative array and its key contain value which is json data, i don't want to use nested foreach loop so used array_walk()

$new_array=array();

array_walk($result, function(&$a, &$key) use($i) {

    $var = '';
    foreach (json_decode($a) as $row_key => $row_value) {

        if ($row_key == 'abc') {
            $new_array[$row_key][] = array(    // push key,value in $new_array
                $row_key => $row_value,
            );
        } else {

           echo $row_key . " : " . $row_value ;
        }
    }
});

Solution

  • Use $new_array by reference:

    array_walk($result, function(&$a, &$key) use($i, &$new_array) {
    

    Also, I don't see any sense in passing $a and $key by reference. Maybe, you show us not full code, and passing by reference $a and $key has sense, but currently, you don't even use $key in the code.

    What's the purpose of passing it then?

    // probably:
    array_walk($result, function($a) use($i, &$new_array) {