我正在使用json_encode()将数组编码为json格式,但是它返回的是对象而不是数组。我想要返回一个数组而不是对象。 有没有人有任何想法?
1) Object
2) Associative array
默认情况下,json_decode() 返回对象类型的值。
但是,如果您想要将值作为数组格式返回,则必须在 json_decode() 中使用 TRUE
作为第二个参数。
e.g,
$decoded_value = json_decode($json_encoded_value, TRUE);
实际上,PHP中的json_encode函数将返回一个JSON格式字符串。
如果您想在PHP中解析JSON格式字符串,则应使用json_decode。
json_decode函数将返回两种类型的数据。对象和关联数组。
json_decode(); 返回类型为对象
json_decode(, TRUE); 返回类型为关联数组
使用此代码解码您编码的 JSON 数据
$encode = $your_json_encoded_data
json_decode($encode, TRUE);
您应该使用带有TRUE
参数的json_decode
,如下面的示例:
$array = array(1,2,3);
$encode = json_encode($array);
$decode = json_decode($encode, TRUE);
$decode
是数组,不是对象。
echo json_encode(array_values($array))
- 是将数组强制转换为对象的最简单方法。 - Eugene