我有数组:
[0] => Height: 3/16
[1] => Color: Standard Red
[2] => Material: Die-cut, pressure-sensitive paper
我要删除这些数字键(0,1,2),并用字符串替换数组元素值中两个点之前的字符串。所以最终结果将是:
[Height] => 3/16
[Color] => Standard Red
[Material] => Die-cut, pressure-sensitive paper
我尝试使用array_values函数解决此问题,但我没有做到,有人可以帮助我吗?
答案 0 :(得分:0)
您可以使用array_reduce
来处理数组。在函数内部,我们使用preg_match
将字符串分成其组成部分(请注意,您可能只使用explode(':', $v)
和trim
即可。
$array = array('Height: 3/16',
'Color: Standard Red',
'Material: Die-cut, pressure-sensitive paper');
$new_array = array_reduce($array,
function ($c, $v) { preg_match('/^([^:]+):\s+(.*)$/', $v, $m);
return array_merge($c, array($m[1] => $m[2]));
},
[]);
print_r($new_array);
输出:
Array (
[Height] => 3/16
[Color] => Standard Red
[Material] => Die-cut, pressure-sensitive paper
)
答案 1 :(得分:0)
<?php
$input =
[
'Height: 3/16',
'Color: Standard Red',
'Material: Die-cut, pressure-sensitive paper'
];
foreach($input as $v) {
list($key, $val) = explode(':', $v, 2);
$output[$key] = trim($val);
}
var_export($output);
输出:
array (
'Height' => '3/16',
'Color' => 'Standard Red',
'Material' => 'Die-cut, pressure-sensitive paper',
)