如何从数组中获取值

时间:2016-05-10 15:46:35

标签: php arrays json

我从我的数据库中提取一个以这种格式保存的数组:

[categories] => [
    {"category":"Exit Sign"},
    {"category":"Leaving"},
    {"category":"Illuminated"},
    {"category":"Sign"},
    {"category":"Red"},
    {"category":"Warning Sign"},
    {"category":"Above"}
]

如何遍历每个{}并获取类别?

编辑:我试图通过json_decode()从我的数据库传递每个JSON数组但是我得到以下错误“json_decode()期望参数1是字符串,给定数组......”任何想法会导致什么?

编辑2:这是我的数据库中只有一行的var_dump输出:

array(1) {
  ["categories"]=>
  string(845) "[{"category":"Built Structure"},{"category":"The Americas"},{"category":"Sky"},{"category":"New York City"},{"category":"Manhattan - New York City"},{"category":"USA"},{"category":"History"},{"category":"Suspension Bridge"},{"category":"Brooklyn - New York"},{"category":"Brooklyn Bridge"},{"category":"Scenics"},{"category":"Skyscraper"},{"category":"River"},{"category":"Downtown District"},{"category":"East River"},{"category":"Cityscape"},{"category":"Bridge - Man Made Structure"},{"category":"City"},{"category":"Lighting Equipment"},{"category":"Arch"},{"category":"Urban Skyline"},{"category":"Architecture"},{"category":"Sunset"},{"category":"Night"},{"category":"Modern"},{"category":"Urban Scene"},{"category":"Tower"},{"category":"Famous Place"},{"category":"Gate"},{"category":"Outdoors"},{"category":"East"},{"category":"Travel"}]"
}

知道了!我必须将$ array ['categories']传递给json_decode,然后才能正常工作。谢谢大家的帮助!

1 个答案:

答案 0 :(得分:3)

嗯,所以你是这个世界的新手。不客气。

让您的数组值为$json。此值是json格式,因此要访问此值,您需要解码它们。您需要使用名为json_decode的函数,该函数有两个参数,第一个是传递变量json的字符串,第二个是传递true或false的bool

当你希望数组作为关联而不是对象时,你必须传递。这里我忽略了第二个选项,所以我的返回数组是对象。

解码你的json字符串后,你有一个数组,现在你必须使用循环foreach来浏览数组的所有元素。正如您在下面的结果数组中看到的那样,数组是多维的,因此在应用foreach循环后,您只需达到第一个深度。要获得category的值,您需要在->之后使用$val,这是第一个深度数组。

$json = '[{"category":"Exit Sign"},{"category":"Leaving"},{"category":"Illuminated"},{"category":"Sign"},{"category":"Red"},{"category":"Warning Sign"},{"category":"Above"}]';

$arr = json_decode($json); //Also you can pass $yourArr['categories'];

foreach($arr as $val){
    echo $val->category."<br/>";
}

解码后的数组如下:

Array
(
    [0] => stdClass Object
        (
            [category] => Exit Sign
        )

    [1] => stdClass Object
        (
            [category] => Leaving
        )

    [2] => stdClass Object
        (
            [category] => Illuminated
        )

    [3] => stdClass Object
        (
            [category] => Sign
        )

    [4] => stdClass Object
        (
            [category] => Red
        )

    [5] => stdClass Object
        (
            [category] => Warning Sign
        )

    [6] => stdClass Object
        (
            [category] => Above
        )

)

<强>结果:

Exit Sign
Leaving
Illuminated
Sign
Red
Warning Sign
Above