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

时间:2018-04-20 14:31:08

标签: php arrays merge array-merge

 Array1
    (
        [a] => apple
        [b] => banana
        [c] => egg

    )
    Array2
    (
          [0] => a
          [1] => b
          [2] => c
     )

我有一些价值

Array(
  0 => "name1"
  1 => "name2" 
      )

我需要的是:

Array(

    "name1" => Array
    (
        [a] => apple
        [b] => banana
        [c] => egg

    )
    "name2" => Array
    (
          [0] => a
          [1] => b
          [2] => c
     )
    )

我只想在它之前创建一个名称,并且名称每次都与数组的长度相同,我的意思是第一个名称必须转到第一个数组,第二个名称必须转到第二个,所以对所有人来说都是如此。

1 个答案:

答案 0 :(得分:2)

您可以使用array_combine

  

通过使用一个数组作为键而另一个数组用于创建数组   值

//values
$arr1 = array(
    array('a' => 'apple', 'b' => 'banana', 'c' => 'egg'),
    array('0' => 'a','1' => 'b','2' => 'c')
);

//keys
$arr2 = Array("name1", "name2");

$result = array_combine( $arr2, $arr1 );

echo "<pre>";
print_r( $result );
echo "</pre>";

这将导致:

Array
(
    [name1] => Array
        (
            [a] => apple
            [b] => banana
            [c] => egg
        )

    [name2] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

)

Doc:array_combine