需要帮助从PHP中的某个数组创建新数组

时间:2016-08-24 21:48:17

标签: php arrays multidimensional-array

请帮我解决问题:

我有三个阵列:

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"
                }
           }
}

1 个答案:

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

)