我有一个动态数组
[
"question" => "test 1",
"question1" => "hello test 1",
"question2" => "hello test 2 checked",
"homepage2" => "homepage",
"question3" => "3 test checked",
"homepage3" => "homepage",
"question4" => "question 4 ? checked",
]
按键是“question”、“question1”...等 和“主页”,“主页1”..等 所以我只想在索引为 Question($number) 并且具有与 homepage($number) 类似的键时仅显示数组中的值
如何让它看起来像下面这样?
[
"question2" => "hello test 2 checked",
"homepage2" => "homepage",
"question3" => "3 test checked",
"homepage3" => "homepage",
]
您可以首先创建一个由后缀数字作为键的数组,并将键具有该后缀数字的所有键/值对的数组存储为值。然后,您将过滤那些具有两个这样的键/值对的内容,并以您需要的格式排列它们:
$arr = [
"question"=> "test 1",
"question1"=> "hello test 1",
"question2"=> "hello test 2 checked",
"homepage2"=> "homepage",
"question3"=> "3 test checked",
"homepage3"=> "homepage",
"question4"=> "question 4 ? checked",
];
$temp = [];
foreach($arr as $key => $value) {
if (preg_match("/^(question|homepage)(\d+)$/", $key, $parts))
$temp[$parts[2]][$parts[0]] = $value;
}
$result = [];
foreach($temp as $num => $pair) {
if (count($pair) == 2) $result = array_merge($result, $pair);
}
print_r($result);
$result
将是:
Array (
"question2" => "hello test 2 checked",
"homepage2" => "homepage",
"question3" => "3 test checked",
"homepage3" => "homepage"
)
查看它在 eval.in 上运行。
但是,我建议采用更符合逻辑的结构,将问题和主页组合成一对(数组),并将其分配给一个键,即该对的编号。在这种情况下,两个循环需要进行微小的更改:
$temp = [];
foreach($arr as $key => $value) {
if (preg_match("/^(question|homepage)(\d+)$/", $key, $parts))
$temp[$parts[2]][$parts[1]] = $value;
}
$result = [];
foreach($temp as $num => $pair) {
if (count($pair) == 2) $result[$num] = $pair;
}
这将给出以下结构:
Array(
"2" => Array(
"question" => "hello test 2 checked",
"homepage" => "homepage"
),
"3" => Array(
"question" => "3 test checked",
"homepage" => "homepage"
)
)
查看它在 eval.in 上运行。
仅使用一次迭代检查相关键来过滤数组行。
strtr()
用于在执行关键搜索之前交换伙伴词。 演示
$mates = [
'question' => 'homepage',
'homepage' => 'question',
];
var_export(
array_filter(
$array,
fn($k) => key_exists(strtr($k, $mates), $array),
ARRAY_FILTER_USE_KEY
)
);
array (
'question2' => 'hello test 2 checked',
'homepage2' => 'homepage',
'question3' => '3 test checked',
'homepage3' => 'homepage',
)
这是对我有用的东西:
<?php
$homePageNum = 2;
$var = array(
"question"=>
"test 1",
"question1"=>
"hello test 1",
"question2"=>
"hello test 2 checked",
"homepage2"=>
"homepage",
"question3"=>
"3 test checked",
"homepage3"=>
"homepage",
"question4"=>
"question 4 ? checked"
);
die($var['question'.$homePageNum]);
?>