我在数组中有数组:
{
"0" => array("key" => "code", "id" => "4", "value" => "yes"),
"1" => array("key" => "parameter", "id" => "4", "value" => "0"),
"2" => array("key" => "code", "id" => "5", "value" => "no"),
etc...
}
这就是我想要做的:我希望有一个维度数组,其中键为“id”,值为“value”。但是,我需要过滤掉键为“参数”的条目。因此,在此示例中,最终数组应如下所示:
{
"4" => "yes",
"5" => "no"
}
我似乎无法弄清楚如何做到这一点。你能帮我一下吗?我尝试在foreach中编写这个foreach,但我无法理解如何过滤数据。
foreach ($settings AS $key => $value) {
$id = null;
$value = null;
foreach ($value AS $key2 => $value2) {
// No idea how to filter out uneccesary entries and save the correct ones
}
$finalArray[$id] = $value;
}
答案 0 :(得分:2)
这应该这样做:
$finalArray = array();
foreach ($settings as $setting) {
if ($setting['key'] != 'parameter') {
$finalArray[$setting['id']] = $setting['value'];
}
}
假设您的所有条目都有键'key','id'和'value'。
答案 1 :(得分:2)
像这样使用array_column
和array_filter
,如果你想过滤更多的密钥,请将它们添加到out_keys
数组中:
<?php
$array = [
["key" => "code", "id" => "4", "value" => "yes"],
["key" => "parameter", "id" => "4", "value" => "0"],
["key" => "code", "id" => "5", "value" => "no"]
];
$out_keys = ['parameter'];
$result = array_column(array_filter($array, function($item) use($out_keys) {
return !in_array($item['key'], $out_keys);
}), 'value', 'id');
echo "<pre>";
print_r($result);
输出:
Array
(
[4] => yes
[5] => no
)
答案 2 :(得分:0)
假设$data
是您的起始数组,下面的代码将在$result
$result = [];
foreach(array_filter($data, function($el){return $el['key']!='parameter';}) as $el){
$result[$el['id']] = $el['value'];
}