我正在尝试使用以下结构构建一个多数组:
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
数组嵌入search data
数组中。
可能拥有多辆车,所以我需要遍历每个用户的所有汽车,生成该数组,并将其放入原始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
您似乎正在通过数据库表创建数组。所以你能不能给出2个或更多的样本数据。如果有示例数据,给出答案会更容易。
编辑:好吧,这可能不是最好的代码,但我认为看到这个后您将能够找到更好的方法
$id = $row['id'];
if (!isset($search_data[$id])){
$search_data[$id] = array();
}
$search_data[$id]['name'] = $row['name'];
$search_data[$id]['location'] = $row['location'];
if (isset($search_data[$id]['cars'])) {
array_push($search_data[$id]['cars'],$row['cars']);
}else{
$search_data[$id]['cars'] = array($row['cars']); //this is where I need to insert another array
}