我有一个这样的数组:
$post = array(
"name" => "John",
"user" => "1" ,
"title" => "hello" ,
"uploader_0_name" => "pic.jpg",
"uploader_0_status" => "done",
"uploader_1_name" => "aaaa.jpg",
"uploader_1_status" => "done",
"uploader_2_name" => "Tulips.jpg",
"uploader_2_status" => "failed",
"uploader_count" => "3"
);
我想在另一个数组中使用uploader_[/d]_name
和uploader_[/d]_name
,例如:
[0] => Array
(
[name] => pic.jpg
[status] => done
)
[1] => Array
(
[name] => aaaa.jpg
[status] => done
)
[2] => Array
(
[name] => Tulips.jpg
[status] => failed
)
在这种情况下,索引为0的数组应该有uploader_0_name,uploader_0_status
我在preg_match
循环中尝试使用foreach
进行了很多操作,但我无法成功
foreach ( $post as $key => $value ) {
$pattern = "/^uploader_[\d]_(name|status)$/";
preg_match( $pattern , $key ,$matches[]);
}
P.S:不幸的是今天我看到了最好的答案和最好的方法被删除了,所以我添加了它,如果有任何人有这样的问题,可以使用:
foreach ($post as $key => $value) {
if (preg_match('/^uploader_(\d)_(name|status)$/', $key, $matches)) {
$result[$matches[1]][$matches[2]] = $value;
}
}
答案 0 :(得分:2)
如果您不想使用正则表达式,请尝试此操作:
$newArr = array();
foreach($post as $key => $val) {
$newKey = explode("_", $key);
if (count($newKey) > 2) {
//this is the status
$innerValue = array_pop($newKey);
//this is the numeric ID _2_ for example
$innerKey = array_pop($newKey);
$newArr[$innerKey][$innerValue] = $val;
}
}
答案 1 :(得分:1)
有一种简单的方法可以不使用硬结构:
$post = array(
"name" => "John",
"user" => "1" ,
"title" => "hello" ,
"uploader_0_name" => "pic.jpg",
"uploader_0_status" => "done",
"uploader_1_name" => "aaaa.jpg",
"uploader_1_status" => "done",
"uploader_2_name" => "Tulips.jpg",
"uploader_2_status" => "failed",
"uploader_count" => "3"
);
//result array;
$arr = array();
//counter
$n = 0;
foreach ($post as $key => $value) {
if(strpos($key, '_name') != false){
$arr[$n]['name'] = $value;
}elseif(strpos($key, '_status') != false){
$arr[$n]['status'] = $value;
$n++;
}
}
print_r($arr);