将索引数组转换为关联数组

时间:2012-09-07 07:21:37

标签: php

  

可能重复:
  What's the most straightforward way in PHP to create an associative array from two parallel indexed arrays?

如何转换索引数组,如:

$a = array("foo", "bar", "hallo", "world");

将关联数组与索引的值相关联,如:

$a = array(
    "a1" => "foo",
    "b5" => "bar",
    "f7" => "hallo",
    "n4" => "world"
);

也许有一些PHP核心功能?

或具有相同keys的变体:

$a = array(
    "key" => "foo",
    "key" => "bar",
    "key" => "hallo",
    "key" => "world"
);

UPD

我希望有一个像array_merge()这样的函数,但接受键数组和值数组来创建结果数组。

2 个答案:

答案 0 :(得分:16)

$keys = array('a1', 'b5', 'f7', 'n4');
$a = array_combine($keys, $a);

数组索引必须是唯一的,因此使用相同的键是不可能的。

答案 1 :(得分:0)

如果密钥是随机的,那么我们可以这样做:

$a = array("foo", "bar", "hallo", "world");

$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$size = strlen( $chars );   
$num="0123456789";

$a_s=array();

foreach($a as $art)
{
    $rand= $chars[ rand( 0, $size - 1 ) ].$num[ rand( 0, 9 ) ];

    $a_s[$rand]=$art;
}

$a=$a_s;
print_r($a);