PHP foreach循环构建多数组
我正在尝试使用此结构构建一个多数组:
Array
(
[2] => Array //this is the user's unique ID
(
[name] => Jack
[location] => Somerville, Massachusetts, United States
[cars] => Array
(
[10] => Toyota //this is the car's unique ID
[11] => Porsche
)
)
[5] => Array
(
[name] => Luke
[location] => Schwelm, North Rhine-Westphalia, Germany
[cars] => Array
(
[1] => Honda
[2] => VW
[5] => Maserati
)
)
[1] => Array
(
[name] => Jabba
[location] => Denver, Colorado, United States
[cars] => Array
(
[3] => Tesla
)
)
)
我正在使用此 foreach
循环,但我坚持将 cars
数组嵌入到 搜索数据< /代码> 数组。
每个用户可能拥有不止一辆汽车,因此我需要循环遍历每个用户的所有汽车,生成该数组,并将其放入原始的 foreach 循环中。
$search_data = array();
foreach ($query->result() as $row) {
$search_data[$row->id] = array(
'name' => $row->name,
'location' => $row->location,
'cars' => array($row->car_id), //this is where I need to insert another array
);
}
return $search_data;
有什么建议如何做到这一点?
感谢您的帮助!
示例表数据
USER NAME LOCATION CARS
2 JACK A TOYOTA
2 JACK A PORSCHE
5 LUKE B HONDA
5 LUKE B VW
5 LUKE B MASERATI
1 JABBA C TESLA
I'm trying to build a multi array with this structure:
Array
(
[2] => Array //this is the user's unique ID
(
[name] => Jack
[location] => Somerville, Massachusetts, United States
[cars] => Array
(
[10] => Toyota //this is the car's unique ID
[11] => Porsche
)
)
[5] => Array
(
[name] => Luke
[location] => Schwelm, North Rhine-Westphalia, Germany
[cars] => Array
(
[1] => Honda
[2] => VW
[5] => Maserati
)
)
[1] => Array
(
[name] => Jabba
[location] => Denver, Colorado, United States
[cars] => Array
(
[3] => Tesla
)
)
)
I am using this foreach
loop but am stuck in getting the cars
array embedded within the search data
array.
Each user may have more than one car so I would need to loop through all cars for each user, generate that array, and put it in the original foreach
loop.
$search_data = array();
foreach ($query->result() as $row) {
$search_data[$row->id] = array(
'name' => $row->name,
'location' => $row->location,
'cars' => array($row->car_id), //this is where I need to insert another array
);
}
return $search_data;
Any suggestions how to do this?
Thanks for helping!
SAMPLE TABLE DATA
USER NAME LOCATION CARS
2 JACK A TOYOTA
2 JACK A PORSCHE
5 LUKE B HONDA
5 LUKE B VW
5 LUKE B MASERATI
1 JABBA C TESLA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看来您正在通过数据库表创建数组。那么能否请您提供 2 个或更多样本数据。如果有样本数据,就更容易给出答案。
编辑:
好吧,这可能不是最好的代码,但我认为您在看到此代码后将能够找到更好的方法
It seems that you are creating the array through a database table. So can you please give 2 or more sample data. it'll be easier to give an answer if sample data is there.
Edit:
Well this might not be the best code but I think you'll be able to figure out a better way after seeing this