简体   繁体   中英

How to convert object data into json string in PHP?

I am getting result in object and want to convert into json and I am not understand how to do this so I need help.

My object looks like this:

Array
(
    [0] => stdClass Object
        (
            [user_id] => 85
            [username] => Chang Sindelar
        )

    [1] => stdClass Object
        (
            [user_id] => 84
            [username] => Ezekiel Watterson
        )

    [2] => stdClass Object
        (
            [user_id] => 83
            [username] => Sylvester Hillebrand
        )
)

And I want to convert into json string. I need result somthing like this:

{"85":"Chang Sindelar","84":"Ezekiel Watterson","83":"Sylvester Hillebrand"}

Any Idea.

Thanks.

You problem is not with the JSON encoding, but the mapping of your objects' properties to an associative array.

Mapping your objects into one associative array can be done using array_reduce :

$array = [
    (object) ['user_id' => 85, 'username' => 'Chang Sindelar'],
    (object) ['user_id' => 84, 'username' => 'Ezekiel Watterson'],
    (object) ['user_id' => 83, 'username' => 'Sylvester Hillebrand']
];

$assoc = array_reduce($array, function($result, $item) {
    $result[$item->user_id] = $item->username;
    return $result;
}, []);

The $assoc variable will now hold an associative array like this:

array(3) {
  [85]=>
  string(14) "Chang Sindelar"
  [84]=>
  string(17) "Ezekiel Watterson"
  [83]=>
  string(20) "Sylvester Hillebrand"
}

To get your JSON, simply run $assoc through json_encode :

$json = json_encode($assoc);
// {"85":"Chang Sindelar","84":"Ezekiel Watterson","83":"Sylvester Hillebrand"}

On type casting you can change them into array like

$array = (array) $my_object;

Or even you can use get_object_vars like

$array = get_object_vars($my_object);

Or from your PDO query result them as array

Use for loop and create an new vector (array), after use json_encode, example:

$vector = array();
$size = count($obj); //$obj contain your "array"
for ($i = 0; $i < $size; $i++) {
   $vector[((string) $obj[$i]->user_id)] = $obj[$i]->username;
}

echo json_encode($vector);

using this function will return your object into an array of properties of that object.

array get_object_vars ( object $object )
return get_object_vars($your_object_variable_here)

Try

foreach($arr as $v) {
 $newarr[$v->user_id] = $v->username;
}
echo json_encode($newarr);

Objects dont JSON encode very well, but you can convert it first to an associative array, and then convert to JSON: eg

$array =  (array) $yourObject;
$jsonstring = json_encode ($array)

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