我正在尝试将多维数组转换为简单数组。我的代码的某些部分是工作的,但是当我必须保留一个子数组时,我迷失了。下面是主数组:
Array
(
[0] => Array
(
[name] => scattr
[value] => 250
)
[1] => Array
(
[name] => scattrtel
[value] => 9830293789
)
[2] => Array
(
[name] => scattrcolor
[value] => #2764C6
)
[3] => Array
(
[name] => scattrta
[value] =>
)
[4] => Array
(
[name] => scattrcb
[value] =>
)
[5] => Array
(
[name] => scattrmcb[1]
[value] => 10
)
[6] => Array
(
[name] => scattrmcb[4]
[value] => 40
)
[7] => Array
(
[name] => scattrmrdo
[value] => 20
)
[8] => Array
(
[name] => scattrselect
[value] => 30
)
[9] => Array
(
[name] => pwpus-shortcode-nonce
[value] => 028c9426c5
)
[10] => Array
(
[name] => _wp_http_referer
[value] => /wp-admin/admin-ajax.php
)
)
然后,PHP将其转换为简单数组:
$new = array();
foreach ( $datas as $data ) { // $datas as being the multidimensional array.
$new[$data['name']] = $data['value'];
}
现在,$new
的print_r
得到:
Array
(
[scattr] => 250
[scattrtel] => 9830293789
[scattrcolor] => #2764C6
[scattrta] => gdkwsdghwkdhgk
[scattrcb] =>
[scattrmcb[1]] => 10
[scattrmcb[4]] => 40
[scattrmrdo] => 20
[scattrselect] => 30
[pwpus-shortcode-nonce] => 028c9426c5
[_wp_http_referer] => /wp-admin/admin-ajax.php
)
所以,我认为我的代码有点工作,但不保留scattrmcb[1]
和scattrmcb[4]
在数组中。应该像这样:
[scattrmcb] => Array
(
[1] => 10
[4] => 40
)
我该怎么做?
谢谢
所以array_column()
会帮你解决大部分问题。我使用正则表达式来获取键和内部数组索引,然后eval() != evil
:
foreach(array_column($datas, 'value', 'name') as $key => $value) {
if(preg_match('/(.*)([d+])$/', $key, $match)) {
eval("$new['{$match[1]}']{$match[2]} = $value;");
} else {
$new[$key] = $value;
}
}
可能是或多或少可读的eval()
:
eval('$new["'.$match[1].'"]'.$match[2].' = $value;');
你需要更多的逻辑:
<?php
$datas = [
['name'=>'scattr', 'value'=>250],
['name'=>'scattrmcb[1]', 'value'=>10],
['name'=>'scattrmcb[4]', 'value'=>40]
];
$new = array();
foreach ( $datas as $data ) { // $datas as being the multidimensional array.
// 'scattrmcb' is special so handle it here
if(substr($data['name'], 0, 9) === 'scattrmcb'){
// Set the 'scattrmcb' index
if(!isset($new[substr($data['name'], 0, 9)])){
$new[substr($data['name'], 0, 9)] = [];
}
// Use preg_replace to set a sub-array to the value between []
$new[substr($data['name'], 0, 9)][preg_replace("/[^0-9]/", "", $data['name'])] = $data['value'];
}
else{
$new[$data['name']] = $data['value'];
}
}
print_r($new);