通过阵列循环?

时间:2014-02-13 13:38:58

标签: php arrays loops

我正在尝试在同一视图上循环浏览不同的数据,有时数据看起来像这样:

[{"id":"3","title":"Collection C","short_title":"CC","looks":[{"id":"6","title":"Look 6","image":null,"sell":null,"description":null,"sort":null,"published":"1","pivot":{"collection_id":"3","look_id":"6"}},{"id":"7","title":"Look 7","image":null,"sell":null,"description":null,"sort":"1","published":"1","pivot":{"collection_id":"3","look_id":"7"}}]},{"id":"1","title":"Collection A","short_title":"CA","looks":[{"id":"2","title":"Look 2","image":null,"sell":null,"description":null,"sort":"0","published":"1","pivot":{"collection_id":"1","look_id":"2"}}]}]

有时它看起来像这样:

{"id":"1","title":"Collection A","thumb":null,"banner":null,"video":"ftfgf","looks":[{"id":"2","title":"Look 2","image":null,"sell":null,"description":null,"sort":"0","published":"1","url":"test","pivot":{"collection_id":"1","look_id":"2"}}]} BESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswy

第二组数据打破了我的循环,这是因为它不在数组本身,如果是这样,我怎么能把它放到一个数组中,所以它是唯一的元素。

或者有更好的方法来解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

那是JSON,不是数组。使用json_decode()将其转换为对象或数组(通过传递true作为第二个参数)。然后迭代它将很简单。

从手册:

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>
The above example will output:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}