john_doe john_doe - 3 months ago 8
PHP Question

Need help create new array from some array in PHP

Please help me below problem:

I have three arrays:

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


Two first arrays have same key and value.

Please help me to create a new array in PHP from three above as below:

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

Answer

try this

<?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);
?>

Output:

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

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

)