2015-09-24 97 views
-4

我有以下的阵列,我要重新安排PHP多维数组清理

Array 
(
    [0] => stdClass Object 
     (
      [feeds_id] => 1338 
      [flag] => 0 
     ) 

    [1] => stdClass Object 
     (
      [feeds_id] => 1339 
      [flag] => 0 
     ) 

    [2] => stdClass Object 
     (
      [feeds_id] => 1339 
      [flag] => 1 
     ) 

) 

我想安排它看起来像这样

[1338] => Array ( 
      [0] => 0 
      ) 
[1339] => Array ( 
      [0] => 0 
      [1] => 1 
      ) 
+0

Have你尝试过什么? – Rizier123

+1

我建议你研究Google上的“将stdClass转换为数组”。当你在尝试所学知识的过程中发现问题时,你会回过头来问一个问题。 –

+1

'foreach($ array as $ v)$ result [$ v-> feeds_id] [] = $ v-> flag;' – deceze

回答

-1

此代码应工作:

$newArray=array(); 
foreach($items as $item){ 
    if(!is_array($newArray[$item->feeds_id])){ 
     $newArray[$item->feeds_id]=array(); 
    } 
    array_push($newArray[$item->feeds_id],$item->flag); 
} 

您应该首先创建一个空数组,用于存储新数据。然后,在foreach里面,你应该使用array_push,但是如果你想要放置数据的子数组不是数组,你应该首先声明它(这就是为什么array_push之前的“if”)

+0

'$ newArray [$ item-> feeds_id] [] = $ item-> flag'会做得很好,并且更加简洁。如果有什么你应该使用'isset'而不是'is_array',否则你会得到很多通知。 – deceze

+0

谢谢@sebastianbarria和deceze。这实际上是我想要的。我仍然不明白为什么有这么多的需求降低这个问题。 – user731144