在PHP数组中将键[0]更改为[Name]?

时间:2018-11-23 23:16:59

标签: php arrays string

我有数组:

[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函数解决此问题,但我没有做到,有人可以帮助我吗?

2 个答案:

答案 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
)

Demo on 3v4l.org

答案 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',
)