[英]How can I use PHP to select data from an array where multiple value equals x?
我如何使用PHP来选择 'type_id' = x and level_id = x or term_id = x?
所有会员计划 'type_id' = x and level_id = x or term_id = x?
例如,我想返回所有Single (type_id = 1)
和Basic (level_id = 1)
成员资格计划。 我试图避免额外的SQL查询,因为数据已经存储在一个数组中,我查找我想要的数据并不容易。
我也试图避免大量的foreach循环。 例如,我最近尝试了以下哪种工作...但是如果我有更多类型而不是我的水平怎么办? 必须有更好的方法,对吗?
<?php
$available_types = array();
$available_levels = array();
foreach ($membership_plans as $plan) {
$available_levels[$plan->level_id] = $plan->level_name;
$available_types[$plan->type_id] = $plan->type_name;
}
$available_types = array_unique($available_types);// Unique Types
$available_levels = array_unique($available_levels);// Unique Levels
foreach ($available_levels as $level_id => $level_name) {// foreach level
foreach ($available_types as $type_id => $type_name) {// list each type with level
echo $level_name.' - '.$type_name;
// find plans tht match type and level
foreach ($plans as $plan) {
// More code goes here, but it didn't work out
}
}
}
?>
我有一个会员计划数组,如下所示:
Array
(
[0] => stdClass Object
(
[id] => 1
[type_id] => 1
[type_name] => Single
[level_id] => 1
[level_name] => Basic
[term_id] => 1
[term_name] => MTM
[name] => SB_1
[description] =>
[rate] => 58
[hidden] => 1
[sort] => 1000
[active] => 1
)
[1] => stdClass Object
(
[id] => 2
[type_id]`enter code here` => 1
[type_name] => Single
[level_id] => 1
[level_name] => Basic
[term_id] => 2
[term_name] => 12 Months
[name] => SB_12
[description] =>
[rate] => 56
[hidden] => 0
[sort] => 1110
[active] => 1
)
[2] => stdClass Object
(
[id] => 14
[type_id] => 1
[type_name] => Single
[level_id] => 3
[level_name] => Premier
[term_id] => 2
[term_name] => 12 Months
[name] => SP_12
[description] =>
[rate] => 76
[hidden] => 0
[sort] => 1310
[active] => 1
)
[3] => stdClass Object
(
[id] => 16
[type_id] => 1
[type_name] => Single
[level_id] => 3
[level_name] => Premier
[term_id] => 4
[term_name] => 28 Months
[name] => SP_28
[description] =>
[rate] => 65.43
[hidden] => 1
[sort] => 1330
[active] => 1
)
[4] => stdClass Object
(
[id] => 19
[type_id] => 2
[type_name] => Dual
[level_id] => 1
[level_name] => Basic
[term_id] => 1
[term_name] => MTM
[name] => DB_1
[description] =>
[rate] => 81
[hidden] => 1
[sort] => 2100
[active] => 1
)
)
您可能想要使用array_filter
array_filter(
$arr,
function($v) {
return (
$v->type_id == 'x'
&& ($v->level_id == 'x' || $v->term_id == 'x')
)
}
)
如果x需要变量你有使用函数($ v)使用($ var){并且可能更好地检查type_id是否存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.