任何人都可以帮助我
我对下面的代码有点问题
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()
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
需要明智地使用这个功能。
正如您在功能描述中看到的那样,
函数的三个参数:
1) 待转换的变量。
2) 作为关联数组返回。
3) Depth: default => 512.表示最大深度为512级(在多维数组或复杂对象的情况下),如果第二个参数设置为true<,子元素将被转换为数组
.
首先用 json_encode() 编码你的变量并使用解码 json_decode() .
json_decode()的第二个参数应设置为 true
。
这 true
意味着返回关联数组而不是原始类型。
伪代码:
$output = json_decode(json_encode($yourVar), TRUE);
关于PHP - 将 foreach 转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40457832/