2016-03-23 98 views
0

如何參加一個陣列是這樣的:PHP:如何將關聯數組分解爲單個數組?

Array 
( 
    [0] => Array 
    ( 
     [id] => 1 
     [BillGroup] => Group A 
    ) 
    [1] => Array 
    ( 
     [id] => 2 
     [BillGroup] => Group B 
    ) 
) 

並動態地把它變成一個這樣的數組:

$params = array('1' => 'Group A', '2' => 'Group B') 

其中 '1' 和 '2' 是從[ID]和' [組1]和[組2]來自[BillGroup]。

我需要能夠通過$params成笨的form_dropdown()輔助函數的第二個參數提供的下拉選項

+0

有時候解決一個問題是,即使在[用戶資料](http://stackoverflow.com/use rs/2844319/abracadaver),*提示,提示*(@abracadaver) – Rizier123

回答

2

您可以使用array_column

$params = array_column ($array , 'BillGroup', 'id'); 

結果:

Array 
(
    [1] => Group A 
    [2] => Group B 
) 

array_combine可用於PHP> = 5.5.0。在以前的版本中,你可以使用array_map

$params = array(); 
array_map 
(
    function ($row) use (&$params) 
    { 
     $params[ $row['id'] ] = $row['BillGroup']; 
    } 
    ,$array 
); 

請注意,我們需要通過引用傳遞$params由於匿名函數內部變量的作用域。


+0

爲什麼'array_combine()'?完全不需要。 – Rizier123

+0

@ Rizier123將'id'的值作爲關鍵字 – fusion3k

+0

我認爲查看'array_column()'的手冊頁將是值得的,*提示* – Rizier123

0
<?php 
print "<pre>"; 
echo "Your Array:<br>"; 
    $array=array(

       array('id'=>1 , 'billgroup'=>'Group A'), 
       array('id'=>2 , 'billgroup'=>'Group B'), 
       array('id'=>3 , 'billgroup'=>'Group C') 

     ); 

print_r($array); 


function recursive($array, $level = 1){ 

    global $temp_data; 

    foreach($array as $key => $value){ 
     //If $value is an array. 
     if(is_array($value)){ 
      //We need to loop through it. 
      recursive($value, $level + 1); 
     } else{ 

      //It is not an array, so print it out. 
      $temp_data[] = $value;          
      // echo $key . ": " . $value, '<br>'; 
     } 
    } 

    return $temp_data; 
} 

recursive($array); 
// Converted Array 
echo "Converted Array:<br>"; 

print_r($temp_data); 

$i=0;$j=1;$len = count($temp_data)/2; 

// Converting Normal Array into Associative 
echo "Normal Array to Associative Array:<br>"; 
for($l=1;$l<=$len;$l++){ 

    $output[$temp_data[$i]]= $temp_data[$j]; 
    $i=$i+2; $j=$j+2; 
} 
print_r($output); 

?> 

OUTPUT:

Your Array: 
Array 
(
    [0] => Array 
     (
      [id] => 1 
      [billgroup] => Group A 
     ) 

    [1] => Array 
     (
      [id] => 2 
      [billgroup] => Group B 
     ) 

    [2] => Array 
     (
      [id] => 3 
      [billgroup] => Group C 
     ) 

) 
Converted Array: 
Array 
(
    [0] => 1 
    [1] => Group A 
    [2] => 2 
    [3] => Group B 
    [4] => 3 
    [5] => Group C 
) 
Normal Array to Associative Array: 
Array 
(
    [1] => Group A 
    [2] => Group B 
    [3] => Group C 
) 
+0

這是適用於各種多維陣列...! –