简体   繁体   中英

php JSON_DECODE for different data length

From mysql, I have a data BLOB data type which has two different scenarios (Please see below). I am trying to put them into a string. Below is the process that I am doing:

1. Query:

$names= $results[0]->name;
print_r($names);

First scenario:

[{"Name":"Mike"},{"Name":"Sean"}]

Second scenario:

{"Name":"Mike Smith","Spaces":"1"}

2. JSON_DECODE

$data =  json_decode(stripslashes($names),true);
print_r($data);

First scenario:

    Array
        (
            [0] => Array
                (
                    [Name] => Mike
                )

            [1] => Array
                (
                    [Name] => Smith
                )
        )

Second scenario:

    Array
        (
            [Name] => Mike Smith
            [Spaces] => 1
        )

3. What I am trying to do: To put them into a string

$string = '';

for ($i=0; $i <sizeof($data) ; $i++){ 
    $row = $data[$i];           
    $name = $row -> Name;           

    if(isset($row -> Spaces)){
        $number = '(' . $row -> Spaces . ')';

    }else{                  
        $number = '';

    };
    $string .=  $name . $number . ', ';

};

//Remove last comma
$refined = rtrim($string,', ');

print_r($refined);

4. ISSUE

The issue I am having is that because the data can have two different scenarios like shown in the "1.Query", I can't predict or generalize it and getting errors like "Trying to get property of non-object".

How can I fix this?

Since you're passing true to the $assoc parameter of json_decode , $row->Name will never be the right syntax, since you have an array, and that's syntax for accessing objects; you want $row['Name'] instead. (It's unusual to put space around the -> by the way.)

However, you have basically the right idea on this line:

if(isset($row -> Spaces)){

For an array, that would instead by:

if(isset($row['Spaces'])){

You can do the same thing to see if you've got a name, or a list of names:

if(isset($row['Name'])) {
    // In scenario B
    echo $row['Name'];
    // check for 'Spaces' etc
} else {
    // In scenario A
    foreach ( $row as $item ) {
        echo $item['Name'];
    }
}

Note my use of a foreach loop here, which is much neater than your for loop for this kind of thing.

Well I'll edit my answer for better understanding

$str1 = '[{"Name":"Mike"},{"Name":"Sean"}]';
$str2 = '{"Name":"Mike Smith","Spaces":"1"}';

$json1 = json_decode($str1, false);
$json2 = json_decode($str2, false);

if(is_object($json1))
    { echo 'json1 is object<br>'; } else
    { echo 'json1 is NOT object<br>'; }

if(is_object($json2))
    { echo 'json2 is object'; } else
    { echo 'json2 is NOT object'; }

http://php.net/manual/en/function.is-object.php

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