PHP多维数组无法正常工作

时间:2017-10-03 14:38:22

标签: php arrays

我想创建此回复

'Points' => array(
    'Point' => array(
                    array(
                          'Type' => 'value',
                          'Zone'   => 'value
                    ),
                    array(
                          'Type' => 'value',
                          'Zone'   => 'value'
                    )
              )  
    )

我的代码给了我这个:

array:1 [▼
  "Points" => array:1 [▼
    "Point" => array:2 [▼
      "Type" => 4
      "Zone" => "Front"
    ]
  ]
]

哪个非常接近,遗憾的是de Points键被覆盖,任何人都知道我做错了什么?

$pointsObject = array();
foreach ($points as $point) {
    $pointsObject['Points']['Point'] = array(
        'Type'  => $point->type,
        'Zone'  => $point->zone
    );
}

dd($pointsObject);

2 个答案:

答案 0 :(得分:3)

您在每个循环中覆盖$ pointsObject [' Points'] [' Point']的值。为了避免覆盖其值,您应该在最后添加[]。例如:

$pointsObject['Points']['Point'][] = array(...);

在每个循环中将新值推送到数组中。

问候。

答案 1 :(得分:1)

试试这个

只需在['Points'] ['Point']

之后添加[]
$pointsObject = array();
foreach ($points as $point) {
    $pointsObject['Points']['Point'][] = array(
        'Type'  => $point->type,
        'Zone'  => $point->zone
    );
}

dd($pointsObject);