Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP—将数据添加到嵌套数组特定索引中的正确方法_Php_Arrays_Json - Fatal编程技术网

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

PHP—将数据添加到嵌套数组特定索引中的正确方法,php,arrays,json,Php,Arrays,Json,向嵌套数组中添加信息的正确/实用方法是什么 将数据推送到数组的特定索引时出现问题。我用PHP读取的JSON文件有foreach循环 $array[] = array(); foreach($json["data"] as $inx => $key) { $field1 = $json["data"][$inx]["field1"]; $field2 = $json["data"][$inx]["field2"]; array_push($

向嵌套数组中添加信息的正确/实用方法是什么

将数据推送到数组的特定索引时出现问题。我用PHP读取的JSON文件有foreach循环

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

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

        array_push($array[$field], $field2);
}
数据应该相似:

18732($field1) {
    123($field2),
    1234($field2),
    12345($field2),
    0983($field2),
    239823($field2),
    238742($field2)
}
如何将重复的
$field1
数据合并到名为
$field1
的数组中

错误消息是:

警告:array_push()要求参数1为数组,在 第71行D:\Installed\Xampp\htdocs\includes\core.php


您的代码看起来几乎正确,但您有:

  • 语法错误:
    $array[]=array(),
  • 打字错误:
    $field
    vs
    $field1
  • 第一次访问时,
    $array[$field1]
    未定义
  • 更正代码:

    $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);
    }
    

    您已经尝试了自己的代码,请说明结果出了什么问题。很抱歉,我太困惑了,所以忘了添加相关信息:警告:array_push()希望参数1为array,第71行的D:\Installed\Xampp\htdocs\includes\core.php中给出了null。请编辑您的问题,将该信息直接添加到其中。关于您所谈论的定义,帮助我解决了该问题。我必须添加“isset”检查是否定义了数组索引。如果没有。它将定义它,然后将信息推送到具有特定索引的数组中。多谢各位。