将数组键设置为另一个数组值的值

问题描述 投票:0回答:2

我有以下内容:

( [0] => 3 [1] => 2 [2] => 12 [3] => 6 [4] => 8 [5] => 7 [6] => 9 [7] => 10 [8] => 5 [9] => 4 ) 

我想使用其中每个值作为关键:

( [0] => 7 [1] => 2 [2] => 10 [3] => 3 [4] => 5 [5] => 6 [6] => 11 [7] => 9 [8] => 4 [9] => 8 ) 

我试过这个:

foreach ($iOrder as $i)
{
    $pOrder[$i] = $pOrder[$p];
    
    $p++;
}

我明白了:

( [12] => 2 [10] => 6 [5] => 5 [4] => 7 ) 
php arrays key
2个回答
12
投票

你的意思是

$result = array_combine($keys, $values);

array_combine()


0
投票

第一个数组,$arr1
( [0] => 3 [1] => 2 [2] => 12 [3] => 6 [4] => 8 [5] => 7 [6] => 9 [7] => 10 [ 8] => 5 [9] => 4 )

第二个数组,$arr2, ( [0] => 7 [1] => 2 [2] => 10 [3] => 3 [4] => 5 [5] => 6 [6] => 11 [7] => 9 [ 8] => 4 [9] => 8 )

如果我理解正确,您想使用 $arr1 的值作为 $arr2 中的键。

$values = array_values($arr1); 

=> 这将为您提供 $arr1 的值。 你可以使用,

array_combine($keys, $values);

因此结果数组将是,

$result_arr = array_combine(array_values($arr1), array_values($arr2));

但是,如果两个数组中的项目数不同,则可能无法按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.