0

What would be the proper / practical way to add information into nested array?

I have a problem pushing a data to specific index of array. I have foreach loop for my JSON file that I'm reading with PHP.

$array[] = array();
foreach($json["data"] as $inx => $key) {

        $field1 = $json["data"][$inx]["field1"];
        $field2 = $json["data"][$inx]["field2"];

        array_push($array[$field], $field2);
}

Data should look similar:

18732($field1) {
    123($field2),
    1234($field2),
    12345($field2),
    0983($field2),
    239823($field2),
    238742($field2)
}

How do I merge duplicate $field1's data to array which is "named" as $field1?

The error message is:

Warning: array_push() expects parameter 1 to be array, null given in D:\Installed\Xampp\htdocs\includes\core.php on line 71

3
  • You already tried your own code, please state what is wrong with the result. Commented Sep 3, 2017 at 9:41
  • Sorry I was so confused so I forgot to add information about that: Warning: array_push() expects parameter 1 to be array, null given in D:\Installed\Xampp\htdocs\includes\core.php on line 71 Commented Sep 3, 2017 at 9:58
  • Please edit your question to add that information directly to it. Commented Sep 3, 2017 at 9:59

1 Answer 1

1

Your code looks almost right, but you have:

  1. A syntax error: $array[]= array();,
  2. A typo:$field vs $field1
  3. And the $array[$field1] is not defined when it is first accessed.

Corrected code:

$array = array();
foreach($json["data"] as $inx => $key) {

        $field1 = $json["data"][$inx]["field1"];
        $field2 = $json["data"][$inx]["field2"];

        if (!isset($array[$field1]))
            $array[$field1] = array();

        array_push($array[$field1], $field2);
}
Sign up to request clarification or add additional context in comments.

1 Comment

About the defining you were talking about helped me to solve the issue. I had to add "isset" check about that if the array index is defined. If not. It will define that and then push information to array with specific index. Thank you a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.