用php提取json数据不起作用

时间:2017-05-04 09:11:47

标签: php json

我有这样的json数据:

{"result":{"total":19,"hits":[{"keyword":"sidney webb"},{"keyword":"dr webb"}]},"status_msg":"OK","status_code":200,"left_lines":1196851}

我需要从json中仅提取关键字。我尝试使用代码没有成功:

$json = '{"result":{"total":19,"hits":[{"keyword":"sidney webb"},{"keyword":"dr webb"}]},"status_msg":"OK","status_code":200,"left_lines":1196851}';

foreach ($json['result'] as $keywords)
{
    echo $keywords['result']['keyword'];
}

2 个答案:

答案 0 :(得分:5)

好像,你忘了用json_decode解码字符串。此外,您可能会遍历[result][hits]而不仅仅是[result]

$json = '{"result":{"total":19,"hits":[{"keyword":"sidney webb"},{"keyword":"dr webb"}]},"status_msg":"OK","status_code":200,"left_lines":1196851}';
$json = json_decode($json, true);

foreach ($json['result']['hits'] as $hit)
{
    echo $hit['keyword'];
}

答案 1 :(得分:-1)

TRY

    $json = '{"result":{"total":19,"hits":[{"keyword":"sidney webb"},{"keyword":"dr webb"}]},"status_msg":"OK","status_code":200,"left_lines":1196851}';
    $jsonp =json_decode($json,TRUE);

    foreach ($jsonp['result'] as $val)
    {
        if(is_array($val) ){
        foreach ($val as $k)
        {
            echo  $k['keyword'];

        }
        }

    }