Handling specific elements in json string using php

I have json like this from a remote url

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

When I try to print the element aliases as follows Im getting errors like "trying to get non-object property ..."

<?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 (Download more) from the result

Plz ... help in advance

+3
source share
3 answers

Use array_pop to output the 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;

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

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

0
source

Here is my solution and it without converting objects to 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 a response only after 6 hours of mail, as I am very new here :)

0
source

All Articles