将多维数组转换为单维

时间:2014-10-15 06:03:40

标签: php

将多维数组转换为单维。 我有一个像这样的多维数组.PHP使用数组完成

Array
(
   [0] => Array
    (
        [0] => Name1 
        [1] => valueOfName1                                               
    )

   [0] => Array
    (
        [0] => Name2 
        [1] => valueOfName2                                               
    )

    [2] => Array
    (
        [0] => Name3                
        [1] => valueOfName3
    )

[3] => Array
    (
        [0] => 
    )

[4] => Array
    (
        [0] =>  Name4               
        [1] =>  valueOfName4
    )

  [5] => Array
    (
        [0] => 
    )

);

我希望像这样的输出......使用任何函数数组

Array
(
  Name1 => valueOfName1                                               
 Name2 => valueOfName2                                               
 Name3 => valueOfName3
 Name4 => valueOfName4

3 个答案:

答案 0 :(得分:0)

试试这段代码:

$newArr = array();

foreach($mainArr as $key=>$value) {

    if(isset($value[0]) && $value[0]!= '' && isset($value[1]) && $value[1] != '') {
        $newArr[$value[0]] = $value[1];
    }
}

print_r($newArr);

答案 1 :(得分:0)

这很简单......在发布问题之前先尝试一下......

$people = array (
                "1" => array (
                                "0" => "greenspan",
                                "1" => 32
                                ),
                "2" => array (
                                "0" => "doe",
                                "1" => 52
                                )
                );

$new_people = array();
while(list($person, $person_array) = each($people))
{
    while(list($person_attribute, $value) = each($person_array))
    {
        $new_people[$person_attribute]  =   $value;
    }

}

print_r($new_people);

答案 2 :(得分:0)

试试这个例子:

<?php // Array representing a possible record set returned from a database 



$records = array(
        array(
            'id' => 2135,
            'first_name' => 'John',
            'last_name' => 'Doe',
        ),
        array(
            'id' => 3245,
            'first_name' => 'Sally',
            'last_name' => 'Smith',
        ),
        array(
            'id' => 5342,
            'first_name' => 'Jane',
            'last_name' => 'Jones',
        ),
        array(
            'id' => 5623,
            'first_name' => 'Peter',
            'last_name' => 'Doe',
        ) );   
        $last_names = array_column($records, 'last_name', 'id'); 
        print_r($last_names); ?>

输出:

Array (
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe )

希望这可能对你有用!!!