2016-08-24 221 views
0
創建一些新的陣列陣列

請幫我下面的問題:需要幫助PHP

我有三個數組:

array(3) { 
    [0]=> 
     array(2) { 
      ["name"]=>string(1) "A", 
      ["location"]=>string(9) "first loc" 
     } 
    [1]=> 
     array(2) { 
      ["name"]=>string(1) "A", 
      ["location"]=>string(9) "second loc" 
    } 
    [2]=> 
     array(2) { 
      ["name"]=>string(1) "B", 
      ["location"]=>string(9) "third loc" 
    } 
} 

兩個第一陣列具有相同的密鑰和值。

請幫我從三個上面創建如下PHP中一個新的數組:

array(2) { 
    [0] => 
     array(1) { 
      ["A"] => 
       array(2) { 
         [0]=> string(9) "first loc", 
         [1]=> string(9) "second loc" 
       } 
      }, 
    [1] => 
     array(1) { 
      ["B"] => 
       array(1) { 
        [0]=> string(9) "third loc" 
       } 
      } 
} 
+0

你沒事用'陣列(2){['A'] => array,['B'] => array}'? –

+0

@PriyeshKumar是的。你可以幫我嗎。謝謝。 –

回答

0

試試這個

<?php 
// sample data to work on 
$a = array(
    0=> array(
     "name"=> "A", 
     "location"=>"0 loc" 
    ), 
    1=> array(
     "name"=> "A", 
     "location"=>"1 loc" 
    ), 
    2=> array(
     "name"=>"B", 
     "location"=>"2 loc" 
    ), 
    3=> array(
     "name"=>"B", 
     "location"=>"3 loc" 
    ), 
    4=> array(
     "name"=>"A", 
     "location"=>"4 loc" 
    ), 
    5=> array(
     "name"=>"B", 
     "location"=>"5 loc" 
    ) 
); 

echo '<pre>'; 

$b = array(); 

foreach($a as $v) { 

    if(isset($b[ $v['name'] ])) { 
     // If 'A', 'B', .. so on key already exist, push this item's location 
     array_push($b[ $v['name'] ], $v['location']) ; 
    } else { 
     // Create new key 
     $b[ $v['name'] ] = array($v['location']); 
    } 
} 
print_r($b); 
?> 

輸出:

Array 
(
    [A] => Array 
     (
      [0] => 0 loc 
      [1] => 1 loc 
      [2] => 4 loc 
     ) 

    [B] => Array 
     (
      [0] => 2 loc 
      [1] => 3 loc 
      [2] => 5 loc 
     ) 

) 
+0

工作完美。非常感謝。 –