使用 foreach 的数组迭代


Array Iteration using foreach

我有一个类似于json数组输出的东西,它像:

{
  "data": [
    {
      "color"
      "size"
      "id"
      "weight"
    },
    {
      "color"
      "size"
      "id"
      "weight"
    },

等等。数组名称称为 $cars。我需要遍历所有数组并获取所有汽车尺寸。

像这样:

foreach ($cars as $value) {
    $carsize=[data][i][size]

谢谢。

确保在使用 json_decode() 时解析为数组,然后像这样迭代数据:

$array = json_decode($json, true);
foreach ($array['data'] as $data) {
    $carsize = $data['size'];
    echo $carsize;
}

$cars = json_decode ($cars)应该做你需要的。