如何在PHP / Laravel中检索嵌套数组数据?

时间:2018-05-28 06:31:40

标签: php laravel

{`
+"insights": array:1 [▼
    0 => {#209 ▼
      +"group": "Provision"
      +"dataset": array:1 [▼
        0 => {#207 ▼
          +"group": "Provision"
          +"set": array:3 [▼
            0 => {#194 ▼
              +"name": "Neutral"
              +"value": 917
            }
            1 => {#203 ▶}
            2 => {#197 ▶}
          ]
        }
      ]
    }
  ]
  +"errorCode": 0
}`

如何在set数组中获取name属性?我尝试了多种方式,但它保持错误返回尝试获取属性非对象

3 个答案:

答案 0 :(得分:2)

假设您向刀片视图提供了$response

$response =    {
    +"insights": array:1 [▼
        0 => {#209 ▼
          +"group": "Provision"
          +"dataset": array:1 [▼
            0 => {#207 ▼
              +"group": "Provision"
              +"set": array:3 [▼
                0 => {#194 ▼
                  +"name": "Neutral"
                  +"value": 917
                }
                1 => {#203 ▶}
                2 => {#197 ▶}
              ]
            }
          ]
        }
      ]
      +"errorCode": 0
    }

您必须在刀片视图中循环访问响应:

@foreach($response->insights as $insight)
   @foreach($insight['dataset'] as $dataset)
       @foreach($dataset['set'] as $set)
           <tr><td>$set['name']</td></tr>
       @endforeach
   @endforeach
@endforeach

答案 1 :(得分:1)

data_get($data, 'insights.0.dataset.0.set.0.name');

如果你有json结束 - 将其转换为数组 - &gt; json_decode(字符串);

答案 2 :(得分:1)

你必须简单地遍历它并用你的名字做任何你想做的事情,

foreach($response->insights as $temp){
   foreach($temp->dataset as $var){
      foreach($var as $obj){
         $name = $obj->name;
      }
   }
}