我是新工作的PHP,我使用foreach循环来遍历解码对象的数组.我想为每次迭代输入一个新数组的值.这是代码的一部分:
//example of array before decoding it [{"id":1,"quantity":12, other values...},{"id":2,"quantity":13,other values...}]
$data = json_decode($request->data);
$newArray = array();
foreach ($data as $key => $value){
$newArray[$key] = $value->{'id'} //[1,2,3....]
}
Run Code Online (Sandbox Code Playgroud)
目前我正在生成一维数组,我需要的是获得这种类型的数组:
[
1 => ['quantity' => $other],
2 => ['quantity' => $other]
]
Run Code Online (Sandbox Code Playgroud)
其他'other'将是我从循环中得到的另一个值$value->{'other'}.我怎样才能生成这个?
我不是100%自信,我是否真的得到你的问题......但这可能是你想要的:
foreach ($data as $key => $value) {
$newArray[$value->id] = ['quantity' => $value->quantity];
}
print_r($newArray);
Run Code Online (Sandbox Code Playgroud)
之后json_decode你有类型的对象stdClass,所以可以访问诸如上面示出的属性.
Die*_*ila -3
您可以使用如下方式附加数组:
foreach($file_data as $value) {
list($value1, $value2, $value3) = explode('|', $value);
$item = array(
'value1' => $value1,
'value2' => $value2,
'value3' => $value3
);
$file_data_array[] = $item;
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看以下内容: 使用方括号语法创建/修改