检查数组中是否存在值(Laravel 或 Php)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35147366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a value exits in array (Laravel or Php)
提问by Funny Frontend
I have this array:
我有这个数组:
$list_desings_ids = array('hc1wXBL7zCsdfMu','dhdsfHddfD','otheridshere');
With a die() + var_dumo() this array return me:
使用 die() + var_dumo() 这个数组返回我:
array:2 [▼
0 => "hc1wXBL7zCsdfMu"
1 => "dhdsfHddfD"
2 => "otheridshere"
]
I want check if a design_id exits in $list_desings_ids array.
我想检查 $list_desings_ids 数组中是否存在 design_id 。
For example:
例如:
foreach($general_list_designs as $key_design=>$design) {
#$desing->desing_id return me for example: hc1wXBL7zCsdfMu
if(array_key_exists($design->design_id, $list_desings_ids))
$final_designs[] = $design;
}
But this not works to me, what is the correct way?
但这对我不起作用,正确的方法是什么?
回答by Hassaan
You can use in_array
for this.
您可以in_array
为此使用。
Try
尝试
$design_id = 'hc1wXBL7zCsdfMu';
$list_desings_ids = array('hc1wXBL7zCsdfMu','dhdsfHddfD','otheridshere');
if(in_array($design_id, $list_desings_ids))
{
echo "Yes, design_id: $design_id exits in array";
}
回答by Qazi
instead array_key_exists
you just type in_array
this will solve your issue
because if you dump your this array
相反,array_key_exists
您只需键入in_array
这将解决您的问题,因为如果您转储此数组
$list_desings_ids = array('hc1wXBL7zCsdfMu','dhdsfHddfD','otheridshere');
output will be,
输出将是,
array(
0 => hc1wXBL7zCsdfMu,
1 => dhdsfHddfD,
2 => otheridshere
)
so your code array_key_exists
will not work, because here in keys 0,1,2
exists, So, you want to check values,so for values, just do this in_array
it will search for your desire value in your mentioned/created array
所以你的代码array_key_exists
将不起作用,因为这里0,1,2
存在键,所以,你想检查值,所以对于值,只要这样做,in_array
它就会在你提到/创建的数组中搜索你想要的值
回答by paranoid
Your array not have key .
try this
您的阵列没有 key 。
尝试这个
foreach($general_list_designs as $key_design=>$design) {
#$desing->desing_id return me for example: hc1wXBL7zCsdfMu
if(in_array($design->design_id, $list_desings_ids))
$final_designs[] = $design;
}
回答by Pratik Bhalodiya
you need to change only your condition replace with that code
您只需要更改您的条件替换为该代码
if(in_array($design->design_id, $list_desings_ids))