Manos Krokos Manos Krokos -4 years ago 199
PHP Question

Warning: json_decode() expects parameter 1 to be string, array given

Here is the code:

<? $fields = json_decode($this->item->extra_fields);
$allowed_fields= array('3','5');
if ( $fields != NULL ) {
foreach ( $fields as $field ) {
if ( in_array($field->id, $allowed_fields ) && $field->value != NULL) {
?>
<span class = "list_for<? echo $field->id; ?>">
<? echo $field->value;?></span><? } } }?>


When I change json_decode to json_encode I get the following error:

Warning: Invalid argument supplied for foreach()...
----------


Everything worked before the upgrade of PHP to 5.4 from 5.3.

I am not a developer so please try to not be too technical. Thanks in advance!

Answer Source

Note that json_decode accepts string and according to the above error you are trying to pass an array to it so if you need to iterate on the fields array you may want to ignore json_decode as it seems that you already have an array.

json_encode accepts array but it gives a string so it give you a warning when you try to iterate on sting

so try the below code.

<? $fields = $this->item->extra_fields; 
$allowed_fields= array('3','5');  
if ( $fields ) { 
foreach ( $fields as $field ) { 
if ( in_array($field->id, $allowed_fields ) && $field->value != NULL) {  
?>
<span class = "list_for<? echo $field->id; ?>">
<? echo $field->value;?></span><? }   } }?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download