我有两个数组。
Array-1
(
[0] => title,size
[1] => color
[2] => length
)
Array-2
(
[size_1] => 100
[color_1] => 200
[material_1] => 480
)
我正在尝试从上面的数组中用php实现下面的数组。
Array
(
[title] => 100
[size] => 100
[color] => 200
[length] => 480
)
答案 0 :(得分:1)
一种稍微简单的方法是循环并分解第一个数组的所有值,然后使用数组填充来创建values数组。
$arr = array('title,size', 'color', 'length');
$b = array('size_1' => 100, 'color_1' => 200, 'material_1' => 480);
$b = array_values($b); // since we don't need the keys, just remove them
$result =[];
foreach($arr as $key => $a){
$temp = explode(",", $a);
$result = array_merge($result, array_combine($temp, array_fill(0, count($temp), $b[$key])));
}
var_dump($result);
答案 1 :(得分:0)
尝试array_combine
创建一个新数组,该数组将从array1中获取键,并从array2中获取值,然后使用foreach
将它们一起迭代,并产生如下所示的期望结果:
<?php
$a = array('title,size', 'color', 'length');
$b = array('size_1' => 100, 'color_1' => 200, 'material_1' => 480);
$c = array_combine($a, $b);
$result = array();
foreach($c as $key => $val) {
if(strpos($key, ',')) {
$temp = explode(',', $key);
foreach($temp as $keys){
$result[$keys] = $val;
}
} else {
$result[$key] = $val;
}
}
echo '<pre>';
print_r($a);
print_r($b);
print_r($c);
print_r($result);
/*
------------------
Output
------------------
$a = Array
(
[0] => title,size
[1] => color
[2] => length
)
$b = Array
(
[size_1] => 100
[color_1] => 200
[material_1] => 480
)
$c = Array
(
[title,size] => 100
[color] => 200
[length] => 480
)
$result = Array
(
[title] => 100
[size] => 100
[color] => 200
[length] => 480
)
*/
?>