谁能帮我呢
我有一个小问题,下面的代码
foreach ($products as $product) {
$product->name;
$product->code;
...
}
使用var_dump($products)
的输出代码array
0 =>
object(stdClass)
...
...
...
1 =>
object(stdClass)
...
...
...
我需要这样的输出
$output = array(
array('name' => 'item1', 'code' => 'code1', 'price' => '10.00'),
array('name' => 'item2', 'code' => 'code2', 'price' => '20.00')
);
为此,有一个函数是php json_decode()
混合json_decode (string $json [, bool $assoc = false [, int $depth= 512 [, int $options = 0]])
需要合理使用这个函数
正如你在函数描述中看到的,
函数的三个形参:
1)要转换的变量。
2)返回关联数组
3)深度:default => 512。表示深度为512级(多维数组或复杂对象),当第二个参数设置为true
时,子元素将被转换为数组。
首先用json_encode()对变量进行编码,然后用using进行解码json_decode () .
json_decode ()的第二个参数应设置为true
。
此true
表示返回关联数组而不是原始类型。
伪代码:
$output = json_decode(json_encode($yourVar), TRUE);