3

I've a json like this from a remote url

[{"Name":"Abcd","Alias":["Bcde","Cdef","Fghi","Jklm","Load more"]}]

When I try to print the elements alias as follows Im getting errors like "Trying to get property of non-object..."

<?php

$json='[{"Name":"Abcd","Alias":["Bcde","Cdef","Fghi","Jklm","Load More"]}]';
$obj=json_decode($json);
foreach($obj->Alias as $val) // Error: Trying to get property of non-object<br/>
echo $val.'<br/>';
?>

The decoded json array is as follows

Array
(
    [0] => stdClass Object
        (
            [Name] => Abcd
            [Alias] => Array
                (
                    [0] => Bcde
                    [1] => Cdef
                    [2] => Fghi
                    [3] => Jklm
                    [4] => Load More
                )

        )

)

I would also like to exclude the last "Alias" element (Load More) from the result

Plz... help thanks in advance

3 Answers 3

2

Use array_pop to pop out last element.

<?php

$json='[{"Name":"Abcd","Alias":["Bcde","Cdef","Fghi","Jklm","Load More"]}]';
$obj=json_decode($json);
$aliases = $obj[0]->Alias;
array_pop($aliases);
foreach($aliases as $alias) print $alias;

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

Comments

0
$str = '[{"Name":"Abcd","Alias":["Bcde","Cdef","Fghi","Jklm","Load more"]}]';
print_r(json_decode($str, true));

See documentation on function arguments on http://php.net/manual/en/function.json-encode.php

1 Comment

json_decode($str, true)) objects will be converted into associative arrays. so how does it helpful to resolve the error plz. thanks
0

Here is my solution and it's without converting objects into associative arrays

   <?php

    $json='[{"Name":"Abcd","Alias":["Bcde","Cdef","Fghi","Jklm","Load More"]}]';
    $obj=json_decode($json);
    $obj = $obj[0];
    foreach($obj->Alias as $val)
    echo $val.'<br/>';

    ?>

I was able to post an answer only after 6hrs of post as I'm very new here :)

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.