2

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 ;
        }
    }
});
user_1234
  • 741
  • 1
  • 9
  • 22

1 Answers1

1

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) {
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • thank you som much you saved me, greate work ,can u please tell me why $new_array should be passed by reference – user_1234 Feb 02 '20 at 15:34
  • 1
    Passing by reference means that __original value__ of variable will be changed. This is just what you need - chnage the original value. On the contrary - passing __by value__ just passes value and does not change the original value. – u_mulder Feb 02 '20 at 15:35