将数组指定为另一个数组的值

时间:2015-12-16 05:20:34

标签: php arrays multidimensional-array delimiter

我有三个数组需要创建一个可以是多维的数组。

第一阵列

Array
(
    [0] => Test_One
    [1] => Test_two
)

第二阵列

Array
(
   [0] => www.link.com
   [1] => www.link2.com
)

第三阵列

Array
(
   [0] => Song1
   [1] => song2
)

我想要什么

Array
(
   [www.link.com] => Array
                     (
                        [0] => Test_one
                        [1] => Song1
                     )
   [www.link2.com] => Array
                     (
                        [0] => Test_two
                        [1] => Song2
                     )
 )

3 个答案:

答案 0 :(得分:2)

假设在所有三个数组中都有相同数量的元素:

<?php
$arr1 = Array
(
    0 => "Test_One",
    1 => "Test_two"
);

$arr2 = Array
(
    0 => "www.link.com",
    1 => "www.link2.com"
);

$arr3 = Array
(
    0 => "Song1",
    1 => "Song2"
);

$final = []; //for versions below PHP 5.4 use $final = array();

foreach($arr2 as $key=>$value) {
    $final[$value] = [$arr1[$key],$arr3[$key]];
}

print_r($final);

将输出:

Array
(
    [www.link.com] => Array
        (
            [0] => Test_One
            [1] => Song1
        )

    [www.link2.com] => Array
        (
            [0] => Test_two
            [1] => Song2
        )

)

更新:简化foreach循环。来自评论@uchiha

答案 1 :(得分:1)

假设你在所有三个数组中都没有相同数量的元素:

<?php
$arr1 = Array
(
    0 => "Test_One",
    1 => "Test_two"
);

$arr2 = Array
(
    0 => "www.link.com",
    1 => "www.link2.com"
);

$arr3 = Array
(
    0 => "Song1",
);

$final = []; //for versions below PHP 5.4 use $final = array();

foreach($arr2 as $key=>$value) {
    if(array_key_exists($key,$arr1)) {
        $final[$value][] = $arr1[$key];
    }
    if(array_key_exists($key,$arr3)) {
        $final[$value][] = $arr3[$key];
    }
}

print_r($final);

输出:

Array
(
    [www.link.com] => Array
        (
            [0] => Test_One
            [1] => Song1
        )

    [www.link2.com] => Array
        (
            [0] => Test_two
        )

)

答案 2 :(得分:0)

希望这有帮助:)

<?php 
$array1 = Array
(
    'Test_One',
    'Test_two'
);


$array2 = Array
(
   'www.link.com',  
   'www.link2.com'
);

$array3 = Array
(
   'Song1',
  'song2'
);

$array4 = array();
$i = 0;
foreach ($array2 as $a2){
    $array4[$a2][] = $array1[$i];
    $array4[$a2][] = $array3[$i];
    $i++;
}
echo "<pre>";
print_r($array4);
?>