Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handling specific elements in a json string using php

Tags:

json

php

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

like image 767
TheKid Avatar asked Aug 13 '26 08:08

TheKid


1 Answers

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;

?>
like image 106
TheMonkeyKing Avatar answered Aug 14 '26 22:08

TheMonkeyKing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!