解析和循环JSON输入字符串

I have the following JSON input (it's in a file called customer.json) but cant seem to loop through the values -

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

The following is the code I've tried and have been working with -

$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; 
}

Any help that can be offered would be greatly appreciated. Thanks,

From the look of the JSON, try this:

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

You are supplying wrong key for the loop, that is not the structure after json_decode. Try a print_r. It will work like:

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

This is how your array looks like

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.
                )

        )

)

Fiddle

Each $post variable is an array containing a 'post' key. You'll need to read them like this:

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

Here's what a print_r looks like:

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.
                        )

                )

        )

)