douxiduan8344 2017-09-03 09:37
浏览 79
已采纳

PHP - 将数据添加到嵌套数组特定索引的正确方法

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

  • 写回答

1条回答 默认 最新

  • douqiaotong8682 2017-09-03 10:01
    关注

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 App的会员连续扣费
  • ¥15 不同数据类型的特征融合应该怎么做
  • ¥15 用proteus软件设计一个基于8086微处理器的简易温度计
  • ¥15 用联想小新14Pro
  • ¥15 multisim中关于74ls192n和DSWPK开关仿真图分析(减法计数器)
  • ¥15 基于8255的交通灯设计
  • ¥15 w3wp,exe 中发生未处理的 Microsoft ,NETFramework 异常。
  • ¥20 C51单片机程序及仿真(加减器)
  • ¥15 AQWA | 水动力分析 二阶波浪力
  • ¥15 c语言题目:成绩管理系统