将值插入循环内的关联数组 [英] Insert values into an associative array within a loop

查看:77
本文介绍了将值插入循环内的关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用php的新手,正在使用foreach循环遍历解码对象数组.我想为每次迭代将值输入到新数组中.这是代码的一部分:

I am new working with php, I am using a foreach loop to traverse an array of decoded objects. I would like to enter values to a new array for each iteration. This is a part of the code:

//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....]
}

在生成一维数组时,我需要获取以下类型的数组:

at the moment I am generating a one-dimensional array, what I need is to obtain an array of this type:

[
    1 => ['quantity' => $other], 
    2 => ['quantity' => $other]
]

其中其他"是我从循环 $ value-> {'other'} 中获得的另一个值.我该如何生成?

where 'other' would be another value that I get from my loop $value->{'other'}. How can I generate this?

推荐答案

无论我是否真的收到您的问题,我都不是100%有信心...但这可能就是您想要的:

I'm not 100% confident, whether I really got your question ... but this is probably what you want:

foreach ($data as $key => $value) {
    $newArray[$value->id] = ['quantity' => $value->quantity];
}

print_r($newArray);

json_decode 之后,您具有类型为 stdClass 的对象,因此您可以访问上面显示的属性.

after json_decode you have objects of type stdClass, so you can access the properties like shown above.

这篇关于将值插入循环内的关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆