2011-05-22 117 views
1

我试图构建一个多阵列采用这种结构: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阵列嵌入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 
+0

shouldent $按行> car_id是一个数组已经后更好的办法弄清楚? – 2011-05-22 04:13:20

+0

我只是把它放在那里以显示我需要帮助的地方 - 让它像那样只会返回一辆车,而不是用户可能拥有的一系列汽车 - 我需要为每个用户循环所有车辆 – pepe 2011-05-22 04:24:53

+0

很难如果汽车在不同的行上分开,那么汽车就会变成一个数组,因为当你把它放在一个数组中时,同一个查询的下一个结果就会浪费,你知道我的想法了吗? – 2011-05-22 04:34:46

回答

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 
    } 
+0

只是在OP的一些示例数据 - 让我知道你在想什么,谢谢 – pepe 2011-05-22 04:23:00

+0

@torr这是我用这个解决方案得到的阵列 Array([2] => Array([name] => Jack [location] = > A [汽车] =>阵列([0] =>保时捷[1] =>丰田))[5] =>阵列([名称] =>卢克[位置] => B [cars] =>阵列([ 0] => Honda [1] => VW [2] => Maserati))[1] => Array([name] => Jabba [location] => C [cars] => Array([0] =>特斯拉))) – sYl3r 2011-05-22 05:51:13

+0

实际上你的想法使用'array_push'对于这种情况非常好 - 不知道其他解决方案是否会比这更有效率 - 感谢您的帮助! – pepe 2011-05-22 14:15:10