PHP:如何将关联数组分解为单个数组?

时间:2016-03-23 23:47:59

标签: php arrays codeigniter

如何使用这样的数组:

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]和'Group 1'而''Group 2'来自[BillGroup]。

我需要能够将$params传递给Codeigniter的form_dropdown()辅助函数作为第二个参数来提供下拉选项

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);

?>

输出:

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
)