2014-02-28 137 views
0

我一直在嘗試將一個數組拆分爲兩個組,當前我的數組看起來像這樣。分裂陣列PHP

Array 
(
    [cities] => Array 
     (
      [0] => Array 
       (
        [id] => 0 
        [storename] => test 
        [notes] => test 
        [rejected] => off 
        [offer] => 
        [time] => 1393585744241 
       ) 

      [1] => Array 
       (
        [id] => 1 
        [storename] => test2 
        [notes] => test2 
        [rejected] => on 
        [offer] => test2 
        [time] => 1393585751264 
       ) 

     ) 

PHP

foreach($array['cities'] as $data) 
{ 
    if($data['rejected'] == "off"){ 

     $rejected = array(); 

     array_push($rejected, $data['id'], $data['storename'], $data['offer']); 


    } 

    if($data['rejected'] == "on"){ 

     $nonerejected = array(); 

     array_push($nonerejected, $data['id'], $data['storename'], $data['offer']); 


    } 


} 

我要去哪裏錯了任何想法?

回答

3

試試這個,

$nonerejected = array(); 
$rejected = array(); 
foreach($array['cities'] as $data) 
{ 
    if($data['rejected'] == "off"){ 
     array_push($rejected, $data['id'], $data['storename'], $data['offer']); 
    } 

    if($data['rejected'] == "on"){ 
     array_push($nonerejected, $data['id'], $data['storename'], $data['offer']); 
    } 
} 

你應該申報$nonerejected$rejected陣列外foreach

+0

由於IM如此血腥的愚蠢! – Brent

2

您反覆重新創建陣列。將$rejected = array()$nonrejected = array()設置爲之前foreach循環。

1

呦創建在每次迭代的陣列到foreach循環。您必須創建$rejected和外循環的$nonerejected,收到:

$nonerejected = array(); 
$rejected = array(); 
foreach($array['cities'] as $data) 
{ 
    if($data['rejected'] == "off"){   

     array_push($rejected, $data['id'], $data['storename'], $data['offer']); 
    } 

    if($data['rejected'] == "on"){   

     array_push($nonerejected, $data['id'], $data['storename'], $data['offer']); 
    } 
}