0

我有以下 JSON 输入(它在一个名为 customer.json 的文件中)但似乎无法遍历这些值 -

{"posts":[
{"post":{"Customer_ID":"A & I","CustomerName":"A & I Products"}},
{"post":{"Customer_ID":"A&A","CustomerName":"A & A Mfg. Co., Inc."}}
]}

以下是我尝试过并一直在使用的代码 -

$inputJSON = file_get_contents('/srv/www/htdocs/sandbox/customer.json');
$parsedJSON = json_decode($inputJSON,true);
$parsedJSON = $parsedJSON['posts'];

foreach ($parsedJSON['post'] as $post) 
{
$custid = $post['Customer_ID'];
$custnm = $post['CustomerName'];
echo $custid; 
echo $custnm; 
}

任何可以提供的帮助将不胜感激。谢谢,

4

3 回答 3

1

您为循环提供了错误的密钥,这不是 json_decode 之后的结构。尝试一个print_r. 它将像这样工作:

foreach ($parsedJSON as $value) 
{
$custid = $value["post"]['Customer_ID'];
$custnm = $value["post"]['CustomerName'];
echo $custid; 
echo $custnm; 
}

这就是你的数组的样子

Array
(
    [0] => Array
        (
            [post] => Array
                (
                    [Customer_ID] => A & I
                    [CustomerName] => A & I Products
                )

        )

    [1] => Array
        (
            [post] => Array
                (
                    [Customer_ID] => A&A
                    [CustomerName] => A & A Mfg. Co., Inc.
                )

        )

)

小提琴

于 2013-10-09T14:02:08.163 回答
0

从 JSON 的外观来看,试试这个:

foreach ($parsedJSON as $post) 
{
 $custid = $post['post']['Customer_ID'];
 $custnm = $post['post']['CustomerName'];
 echo $custid; 
 echo $custnm; 
}
于 2013-10-09T14:00:14.663 回答
0

每个$post变量都是一个包含'post'键的数组。您需要像这样阅读它们:

foreach ($parsedJSON as $post)
{
    $custid = $post['post']['Customer_ID'];
    $custnm = $post['post']['CustomerName'];
    echo $custid;
    echo $custnm;
}

这是 a 的print_r样子:

Array
(
    [posts] => Array
        (
            [0] => Array
                (
                    [post] => Array
                        (
                            [Customer_ID] => A & I
                            [CustomerName] => A & I Products
                        )

                )

            [1] => Array
                (
                    [post] => Array
                        (
                            [Customer_ID] => A&A
                            [CustomerName] => A & A Mfg. Co., Inc.
                        )

                )

        )

)
于 2013-10-09T14:04:22.357 回答