[英]If condition to check value of multiple column array php
我试图获取is_activated
列键的值。 但是无法获得确切的值。 尝试过array_search()
查看阵列
需要检查所有is_activated
键的值是否为1。
Array
(
[0] => Array
(
[first_name] => Array
(
[0] => john
)
[is_activated] => Array
(
[0] => 0
)
)
[1] => Array
(
[first_name] => Array
(
[0] => mark
)
[is_activated] => Array
(
[0] => 1
)
)
[2] => Array
(
[first_name] => Array
(
[0] => pretik
)
[is_activated] => Array
(
[0] => 0
)
)
)
我已经尝试过以下解决方案,但无法获得结果。
$is_user_activated = array_search(1,array_column($activity,'is_activated'));
if($is_user_activated == 1) { echo 'yes'; }
else { echo 'no'; }
我认为您想循环执行此操作,而不是使用array_search。 使用foreach()获得所需的结果:
foreach($yourArray as $item) {
if($item['is_activated'][0] == 1) {
echo 'yes';
} else {
echo 'no';
}
}
您可以将array_filter()
用于此类任务,它允许使用回调过滤器函数:
<?php
$data = [
[
'first_name' => ['john'] ,
'is_activated' => [0]
],
[
'first_name' => ['mark'],
'is_activated' => [1]
],
[
'first_name' => ['pretik'],
'is_activated' => [0]
]
];
$matches = array_filter($data, function($entry) {
return in_array(1, $entry['is_activated']);
});
var_dump($matches);
输出为:
array(1) {
[1]=>
array(2) {
["first_name"]=>
array(1) {
[0]=>
string(4) "mark"
}
["is_activated"]=>
array(1) {
[0]=>
int(1)
}
}
}
之所以有点尴尬,是因为您的初始数据具有一个非常奇怪的结构:元素的值是本身保存实际值而不是标量值本身的数组 。 这使得搜索比“正常”情况下的搜索更为复杂。 因此,请好好看看,如果您可以修复该奇怪的结构,而不是能够使用更简单的搜索方法。
您可以通过array_filter
获取激活的用户:
$activated = array_filter($users, function($record) {
return reset($record['is_activated']) == 1;
});
这只会保留被激活的用户,然后您可以简单地对数组进行计数以查看是否有任何激活的用户:
echo count($activated) ? 'yes' : 'no';
此处的示例: http : //ideone.com/mMuJcO
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.