[英]Split array to create an associative array
I have an array that looks like this: 我有一个看起来像这样的数组:
a 12 34
b 12345
c 123456
So the array looks like 所以阵列看起来像
$array[0] = "a 12 34"
$array[1] = "b 12345"
$array[2] = "c 123456"
I am trying to create an associative array such that 我正在尝试创建一个关联数组
[a] => 12 34
[b] => 12345
[c] => 123456
Can I possibly split the array into two, one for containing "a, b, c" and another for their contents and use the array_combine() ?
我可以将数组分成两个,一个用于包含“a,b,c”,另一个用于包含其内容并使用array_combine() ? Or are there any other ways?
或者还有其他方法吗?
You can do that within a loop like the snippet below demonstrates.
您可以在循环中执行此操作,如下面的代码段所示。 Quick-Test here:
在这里快速测试:
$array = array("a 12 34", "b 12345", "c 123456");
$array2 = array();
foreach($array as $data){
preg_match("#([a-z])(\s)(.*)#i", $data, $matches);
list(, $key, $space, $value) = $matches;
$array2[$key] = $value;
}
var_dump($array2);
// YIELDS::
array(3) {
["a"]=> string(5) "12 34"
["b"]=> string(5) "12345"
["c"]=> string(6) "123456"
}
Or using a Blend of
array_walk()
andarray_combine()
which can be Quick-Tested Here.或者使用
array_walk()
和array_combine()
的Blend,它可以在这里进行Quick-Tested。
<?php
$array = array("a 12 34", "b 12345", "c 123456");
$keys = array();
array_walk($array, function(&$data, $key) use (&$keys){
$keys[] = trim(preg_replace('#(\s.*)#i', '', $data));;
$data = trim(preg_replace('#(^[a-z])#i', '', $data));
});
$array = array_combine($keys, $array);
var_dump($array);;
// YIELDS::
array(3) {
["a"]=> string(5) "12 34"
["b"]=> string(5) "12345"
["c"]=> string(6) "123456"
}
You can do it without any difficulty :) A simple loop is possible to do it. 你可以毫无困难地做到这一点:)一个简单的循环就可以做到。
explode(' ', $row, 2)
, strstr
, substr
, ...) ? explode(' ', $row, 2)
, strstr
, substr
,...)? $array[$key] = $value;
$array[$key] = $value;
You could use a combination of array_map
, array_column
and array_combine
: 您可以使用
array_map
, array_column
和array_combine
的组合:
$array = array_map(function ($v) { return explode(' ', $v, 2); }, $array);
$array = array_combine(array_column($array, 0), array_column($array, 1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.