在同一行中使用explode()时如何访问数组索引?
我无法理解这个......
比如说,我们像这样爆炸整个事情:
$extract=explode('tra-la-la', $big_sourse);
然后我们想要获取索引 1 处的值:
$finish = $extract[1];
我的问题是如何一次性得到它,这么说吧。与此类似的东西:
$finish =explode('tra-la-la', $big_sourse)[1]; // 不起作用
像下面这样的东西会像魅力一样起作用:
$finish = end(explode('tra-la-la', $big_sourse));
//或
$finish = array_shift(explode('tra-la-la', $big_sourse));
但如果该值位于中间某个位置怎么办?
Can't wrap my head around this...
Say, we explode the whole thing like so:
$extract = explode('tra-la-la', $big_sourse);
Then we want to get a value at index 1:
$finish = $extract[1];
My question is how to get it in one go, to speak so. Something similar to this:
$finish = explode('tra-la-la', $big_sourse)[1]; // does not work
Something like the following would work like a charm:
$finish = end(explode('tra-la-la', $big_sourse));
// or
$finish = array_shift(explode('tra-la-la', $big_sourse));
But what if the value is sitting somewhere in the middle?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
函数数组解引用已在 PHP 5.4 中实现。对于旧版本,这是 PHP 解析器中的一个限制,已在此处修复,所以恐怕目前没有办法解决这个问题。
Function Array Dereferencing has been implemented in PHP 5.4. For older version that's a limitation in the PHP parser that was fixed in here, so no way around it for now I'm afraid.
类似的东西:
虽然我不认为它比写成两行更好/更清晰/更漂亮。
Something like that :
Though I don't think it's better/clearer/prettier than writing it on two lines.
您可以使用
list
:[1]
实际上会是数组中的第二个元素,不确定你是否真的这么想。如果是这样,只需将另一个变量添加到列表构造中(如果愿意,可以省略第一个变量)you can use
list
:[1]
would actually be the second element in the array, not sure if you really meant that. if so, just add another variable to the list construct (and omit the first if preferred)我的建议 - 是的,我已经想出了一些办法 - 是使用该功能允许的额外参数。如果设置为正值,则返回的数组将包含最多 limit 个元素,最后一个元素包含字符串的其余部分。因此,如果我们想要获取索引 2 处的值(当然,我们确定我们想要的值事先就在那里),我们只需按如下方式操作:
explode 将返回一个包含最大值的数组三个元素,所以我们“结束”到我们要查找的最后一个元素,索引为 2 - 我们就完成了!
My suggest - yes, I've figured out something -, would be to use an extra agrument allowed for the function. If it is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string. So, if we want to get, say, a value at index 2 (of course, we're sure that the value we like would be there beforehand), we just do it as follows:
explode will return an array that contains a maximum of three elements, so we 'end' to the last element which the one we looked for, indexed 2 - and we're done!