PHP foreach循环构建多个数组

时间:2011-05-22 04:02:27

标签: 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
                (
                    [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

1 个答案:

答案 0 :(得分:2)

您似乎正在通过数据库表创建数组。那么请你提供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
    }