简体   繁体   中英

while decoding and getting json value i am getting error?

In productoptions coloumn in database table , i insert the value like below

[{"value":["Color","size",""]},{"Color":["Red","Blue","white"],"size":["L","XL"]},{"type":["Dropdown","Checkbox",""]}]

After that i got the option values

$opt =$value->ProductOptions;

Then i decode the json value by using following

$jsonvalue = json_decode($opt);

then i got value like below.

Array ( [0] => stdClass Object ( [value] => Array ( [0] => Color [1] => size [2] => ) ) [1] => stdClass Object ( [Color] => Array ( [0] => Red [1] => Blue [2] => white ) [size] => Array ( [0] => L [1] => XL ) ) [2] => stdClass Object ( [type] => Array ( [0] => Dropdown [1] => Checkbox [2] => ) ) )

After decoding i am trying to get particular object(color, size etc)

foreach ($jsonvalue as $key => $values) {
  print_r($vales->Color);
}

But i am error like below:

Message: Undefined property: stdClass::$Color

I am get value

value => color,size 

After that in need pass above value dynamically and get

color => red,blue,white 

The JSON structure is a bit odd, you have mixed data and structures.

But if you use print_r($jsonvalue); you can see how the arrays and objects are laid out, this shows that the [0] item has the value element, and the [1] has the data indicated by the values, so...

One of the items in your value element is "" , this can cause problems so you may want to add a check to ignore empty items.

foreach ( $jsonvalue[0]->value as $types ) {
    if ( !empty($types) )   {
        echo $types.PHP_EOL;
        print_r($jsonvalue[1]->{$types});
    }    
}

gives you...

Color
Array
(
    [0] => Red
    [1] => Blue
    [2] => white
)
size
Array
(
    [0] => L
    [1] => XL
)

Try :

foreach ($jsonvalue as $key => $values) {
  print_r($vales->{$key});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM