我有一个数组它的结构是这样的
- foo = stuff我们不关心这个例子
- foo1_value
- foo1_label
- foo1_unit
- foo2_value
- foo3_label
- foo3_value
你能想出一个快速的方法让它看起来像那样吗?
- foo
- foo1
- 标签
- foo2
- foo3
- 标签
我实际上正在尝试这样做:
array_walk($array, function($val, $key) use(&$nice_array) {
$match = false;
preg_match("/_label|_value|_unit|_libelle/", $key, $match);
if (count($match)) {
list($name, $subName) = explode('_', $key);
$nice_array[$name][$subName] = $val;
} else {
$nice_array[$key] = $val;
}
});
echo '<pre>';
print_r($nice_array);
echo '</pre>';
这是工作的,我只需要反思一下foo_foo_label这一切都很好
可以在数组键上使用explode
,如下所示:
$newArray = array();
foreach ( $array as $key => $value )
{
$parts = explode('_', $key);
$newArray[$parts[0]][$parts[1]] = $value;
}
编辑:在注释中详细更新。将处理您的foo_foo_value
以及foo
和foo_foo
情况。如果您只是将结果传递给第二个数组,那么确实没有理由使用array_walk。
$newArray = array();
foreach ( $array as $key => $value ) {
if ( preg_match('/_(label|value|unit)$/', $key) === 0 ) {
$newArray[$key] = $value;
continue;
}
$pos = strrpos($key, '_');
$newArray[substr($key, 0, $pos)][substr($key, $pos+1, strlen($key))] = $value;
}
您可以做的是循环遍历数组,并在_
上拆分(explode()
)每个键来构建您的新数组。
$newArray = array();
foreach($oldArray as $key=>$value){
list($name, $subName) = explode('_', $key);
if($subName !== NULL){
if(!isset($newArray[$name])){
$newArray[$name] = array();
}
$newArray[$name][$subName] = $value;
}
else{
$newArray[$name] = $value;
}
}
$nice_array = array();
array_walk($array, function($val, $key) use(&$nice_array) {
$match = false;
preg_match("/_label|_value|_unit|_libelle/", $key, $match);
if (count($match)) {
$tname = preg_split("/_label$|_value$|_unit$|_libelle$/",$key);
$name = $tname[0];
$subName = substr($match[0],1);
$nice_array[$name][$subName] = $val;
} else {
$nice_array[$key] = $val;
}
});