我有2个数组,一个有键,另一个有数字键,如何复制键,按照确切的顺序替换数字键?
带数字键的数组
Array
(
[0] => ABCDEFG
[1] => This is my description
[2] => 12.00
[3] => 30.00
[4] => My supplier
[5] => My brand
[6] => Shoes
[7] =>
)
数组2
Array
(
[productcode] => Product Code
[productitemdesc] => Description
[retailsalesprice] => Selling Price
[currentcost] => Unit Cost
[supplier] => Supplier
[productbrand] => Brand
[productcategory] => Category
[productgroup] => Group
)
我想要这样的东西
Array
(
[productcode] => ABCDEFG
[productitemdesc] => This is my description
[retailsalesprice] => 12.00
[currentcost] => 30.00
[supplier] => My Supplier
[productbrand] => My Brand
[productcategory] => Shoes
[productgroup] =>
)
php有现成的功能吗?试过array_fill_keys但似乎不是我想要的。
答案 0 :(得分:5)
您可以使用函数array_combine()
将第二个数组中的键(对于以下示例称为$array_keys
)与第一个数组中的值(称为$array_values
)组合在一起:< / p>
示例:
$combined = array_combine(array_keys($array_keys), $array_values);
print_r($combined);
这将完全按照您的描述打印出阵列。
答案 1 :(得分:0)
array_combine
方式好多了,但你也可以使用这个功能。这将允许您根据需要修改值。
function custom_combine($numeric_array, $keyed_array)
{
$temp = array();
$i=0;
foreach($keyed_array as $key=>$val)
{
if(isset($numeric_array[$i]))
$temp[$key] = $numeric_array[$i];
else
$temp[$key] ='';
$i++;
}
return($temp);
}
答案 2 :(得分:0)
其他答案肯定更有效,但如果你想学习如何手动循环数组,这样的事情应该有效:
<?php
// The original array
$arr1 = array(
0 => 'ABCDEFG',
1 => 'This is my description',
2 => '12.00',
3 => '30.00',
4 => 'My supplier',
5 => 'My brand',
6 => 'Shoes',
7 => '',
);
// The second array
$arr2 = array(
'productcode' => 'Product Code',
'productitemdesc' => 'Description',
'retailsalesprice' => 'Selling Price',
'currentcost' => 'Unit Cost',
'supplier' => 'Supplier',
'productbrand' => 'Brand',
'productcategory' => 'Category',
'productgroup' => 'Group',
);
// Pre-define the new array to avoid errors
$arr_new = array();
// Manually create a value to increment during our foreach loop
$increment = 0;
// Loop through each value in $arr2
foreach ($arr2 as $key2 => $value2) {
// If the key is set in $arr1, assign the value from $arr1 and the key from $arr2
// to the new array
if (isset($arr1[$increment])) {
$arr_new[$key2] = $arr1[$increment];
}
// Increment the value regardless of whether it was found in $arr1 or not
$increment++;
}
// Remove this if you want... It just displays the values found in $arr_new
print_r($arr_new);
答案 3 :(得分:0)
我测试了它并且工作:
<?php
$a=array(
0 => "ABCDEFG",
1 => "This is my description",
2 => "12.00",
3 => '30.00',
4 => 'My supplier',
5 => 'My brand',
6 => 'Shoes',
7 => '',
)
;
$b=array
(
'productcode' => 'Product Code',
'productitemdesc' => 'Description',
'retailsalesprice' => 'Selling Price',
'currentcost' => 'Unit Cost',
'supplier' => 'Supplier',
'productbrand' => 'Brand',
'productcategory' => 'Category',
'productgroup' => 'Group',
);
$j=0;
foreach ($b as $i => $value) {
$b[$i]=$a[$j];
$j++;
}
var_dump($b);
&GT;
答案 4 :(得分:-1)
你可以使用array_combine()
$array3=array_combine($array2,$array1);
print_r($array3);