0

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,

1
  • 1
    what does print_r($parsedJSON) say? Commented Oct 9, 2013 at 13:58

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

                )

        )

)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.