2015-04-20 44 views
1

我在绑定..PHP 2d数组推送问题

这是我想要的输出;

Array 
(
[country] => Array(
        [0] => England 
        [1] => Channel Islands 
       ) 
[gor] => Array(
        [0] => North East 
        [1] => North West 
       ) 
[parliamentaryconstituency] => Array(
        [0] => Aldershot 
        [1] => Aldridge-Brownhills 
       ) 
) 

这就是我现在所拥有的;

Array 
(
[0] => Array 
    (
     [country] => England 
    ) 
[1] => Array 
    (
     [country] => Channel Islands 
    ) 
[2] => Array 
    (
     [gor] => North East 
    ) 
[3] => Array 
    (
     [gor] => North West 
    ) 
[4] => Array 
    (
     [parliamentaryconstituency] => Aldershot 
    ) 
[5] => Array 
    (
     [parliamentaryconstituency] => Aldridge-Brownhills 
    ) 
) 

我的代码是;

foreach ($input as $key => $value) { 
    foreach ($value as $subkey => $subvalue) { 
     switch ($key) 
     { 
      case 'country': 
       $country = Country::description($subvalue)->get()->first(); 
       array_push($new_input, array('country' => $country->description)); 
       break;      
      case 'gor': 
       $gor = Gor::description($subvalue)->get()->first(); 
       array_push($new_input, array('gor' => $gor->description)); 
       break; 
      case 'parlc': 
       $parliamentaryconstituency = ParliamentaryConstituency::description($subvalue)->get()->first(); 
       array_push($new_input, array('parliamentaryconstituency' => $parliamentaryconstituency->description)); 
       break; 
     } 
    } 
} 

我认为array_push($new_input['country'], $country->description);并具有$new_input['country']上述foreach秒,但将输出,如果没有国家都选择了一个空的国家数组,我宁愿它不是,如果是这样的话,在所有出现。

回答

2

你可以试试这个:

$result = array(); 
foreach ($input as $key => $value) { 
    foreach ($value as $subkey => $subvalue) { 
     switch ($key) 
     { 
      case 'country': 
       $country = Country::description($subvalue)->get()->first(); 
       if ($country) { 
        $result['country'][] = $country; 
       } 
       break; 
      case 'gor': 
       $gor = Gor::description($subvalue)->get()->first(); 
       if ($gor) { 
        $result['gor'][] = $gor; 
       } 
       break; 
      case 'parlc': 
       $parliamentaryconstituency = ParliamentaryConstituency::description($subvalue)->get()->first(); 
       if ($parliamentaryconstituency) { 
        $result['parliamentaryconstituency'][] = $parliamentaryconstituency; 
       } 
       break; 
     } 
    } 
} 
print_r($result); 
0

array_push始终在数组的末尾添加一个新元素。取而代之的是,像这样

$result = array("country" => array(), "gor" => array(), etc); 

所有键和在循环假设你要插入的值初始化数组是$值不

$result[$key][] = $value 

或者如果你喜欢使用array_push

array_push($result[$key], $value);