PHP foreach that returns keys only(PHP foreach 只返回键)
问题描述
可能没有任何意义但仍然可能有一个聪明的答案的理论问题.
Theoretical question that perhaps does not make any sense but still, maybe there is a clever answer.
我想遍历数组并获取它的键和带有它们的东西.我所做的一个简单的例子:
I want to iterate through array and get its keys and to something with them. A quick example of what I do:
foreach($array as $key => $value) {
$other_array[$key] = 'something';
}
现在,PHP Mess Detector 尖叫着 $value 在此范围内未使用.因此,我在想,这可能不是访问我的 array 的 keys 的最佳方式.
Now, PHP Mess Detector screams that $value is unused in this scope. Therefore I was thinking that perhaps this is not the best way to access keys of my array.
知道如何在不不必要地从我的 array 中取出 values 的情况下做到这一点吗?它是否有任何显着的性能影响......或者我可能只是偏执,应该继续而不用浪费任何人的时间来回答愚蠢的问题:)
Any idea how to do it without unnecessarily taking out values out of my array? Does it have any significant performance impact ... or perhaps I am just being paranoid and should carry on without wasting anyone's time with stupid questions :).
推荐答案
你可以这样做
foreach(array_keys($array) as $key) {
// do your stuff
}
这将使 foreach 迭代由数组中的键而不是实际数组组成的数组.请注意,从性能的角度来看,它可能不会更好.
That would make the foreach iterate over an array consisting of the keys from your array instead of the actual array. Note that it's probably not better from a performance standpoint though.
这篇关于PHP foreach 只返回键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP foreach 只返回键
基础教程推荐
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何替换eregi() 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
