PHP foreach循环构建多数组

PHP foreach循环构建多数组,php,arrays,loops,multidimensional-array,foreach,Php,Arrays,Loops,Multidimensional Array,Foreach,我正在尝试使用以下结构构建多阵列: Array ( [2] => Array //this is the user's unique ID ( [name] => Jack [location] => Somerville, Massachusetts, United States [cars] => Array (

我正在尝试使用以下结构构建多阵列:

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

看起来您是通过数据库表创建数组的。所以,你能给出两个或更多的样本数据吗。如果有样本数据,给出答案会更容易

编辑: 这可能不是最好的代码,但我认为在看到这一点后,您将能够找到更好的方法

$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
    }

$row->car\u id应该已经是一个数组了吗?我把它放在那里是为了显示我需要帮助的地方-这样只会返回一辆车,而不是一个用户可能拥有的车的数组-我需要循环遍历每个用户的所有车如果它在不同的行上分开,很难将车放入一个数组中,因为当你把它放入一个数组中时,同一查询的下一个结果被浪费了,你明白我的意思吗?只需在OP中输入一些样本数据-让我知道你的想法,thanks@torr这是我用这个解决方案数组得到的数组([2]=>array([name]=>Jack[location]=>A[cars]=>array([0]=>Porsche[1]=>Toyota))[5]=>array([name]=>Luke[location]=>B[cars]=>阵列([0]=>Honda[1]=>VW[2]=>Maserati))[1]=>阵列([name]=>Jabba[location]=>C[cars]=>阵列([0]=>Tesla)))实际上你使用
Array\u push
的想法非常适合这种情况-不确定其他解决方案是否比这更有效-谢谢你的帮助!