检查某个值是否在数组的特定键中
我是使用数组的新手,所以我需要一些帮助。从数组中仅获取一个值。我有一个看起来像这样的原始数组:
$array1= Array(
[0] => 1_31
[1] => 1_65
[2] => 29_885...)
我想做的是搜索并返回下划线后面的值。我已经弄清楚如何将该数据放入第二个数组并将值作为新数组返回。
foreach($array1 as $key => $value){
$id = explode('_',$value);
}
这给了我:
Array ( [0] => 1 [1] => 31 )
Array ( [0] => 1 [1] => 65 )
Array ( [0] => 29 [1] => 885 )
我还可以使用 $id[1]
获取 id 或下划线后的部分的列表,我只是不确定这是否是最好的方法以及是否是如何进行搜索。我尝试过使用 in_array()
但搜索整个数组,但我无法让它只搜索数组的一个键。
任何帮助都会很棒。
I'm new to working with arrays so I need some help. With getting just one vaule from an array. I have an original array that looks like this:
$array1= Array(
[0] => 1_31
[1] => 1_65
[2] => 29_885...)
What I'm trying to do is seach for and return just the value after the underscore. I've figured out how to get that data into a second array and return the vaules as a new array.
foreach($array1 as $key => $value){
$id = explode('_',$value);
}
which gives me:
Array ( [0] => 1 [1] => 31 )
Array ( [0] => 1 [1] => 65 )
Array ( [0] => 29 [1] => 885 )
I can also get a list of the id's or part after the underscore by using $id[1]
I'm just not sure if this is the best way and if it is how to do a search. I've tried using in_array()
but that searches the whole array and I couldn't make it just search one key of the array.
Any help would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不得不同意。如果您希望查看数组中是否存在某个值,则只需使用“array_key_exists”函数,如果它返回 true,则可以使用该值。
I would have to agree. If you wish to see is a value exists in an array however just use the 'array_key_exists' function, if it returns true use the value for whatever.
如果下划线后面的部分是唯一的,则将其作为新数组的键:
因此您可以使用 isset($newArray[$mykey]) 检查键是否存在,这样会更高效。
If the part after underscore is unique, make it a key for new array:
So you can check for key existence with
isset($newArray[$mykey])
, which will be more efficient.您可以使用
preg_grep()
来 grep 一个数组:输出:
参见 http://ideone. com/3Fgr8
You can use
preg_grep()
to grep an array:Outputs:
See http://ideone.com/3Fgr8
我想说你做得和其他人一样好。
编辑
替代方法:
I would say you're doing it just about as well as anyone else would.
EDIT
Alternate method: