使用list()或类似方法实现左侧分配,导致除最后一个参数外的所有其他参数组成一个数组 [英] Using list() or similar to achieve left-hand assignment resulting in an array for all other parameters than the last

查看:46
本文介绍了使用list()或类似方法实现左侧分配,导致除最后一个参数外的所有其他参数组成一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是针对以下问题的后续问题:

This is a follow-up question to:

使用list()或类似方法在保留数组的同时保留除第一个参数以外的所有其他参数的左手分配

情况

$str = 'all.your.base';
list($a, $b, $c) = explode('.', $str);

$ a $ b $ c 将进行相应设置。

$a, $b and $c will be set accordingly.

但是,我想要实现的是这样:

However, what i want to achieve is this:

$str = 'all.your.base';
list($prev, $final) = explode('.', $str);

之后, $ final 应该包含'base' $ prev 应该是一个看起来像这样的数组: ['all', 'your']

Whereas afterwards $final should contain 'base' and $prev should be an array that looks like this: ['all', 'your']

虽然可以通过其他方式轻松完成,但我正在寻找诸如 list之类的解决方案()也许我并不知道,它可以单行或以最少的代码实现。可能涉及交错的 explode() implode 调用以及某些字符串反转吗?

While this can be done easily by other means, i look for a solution such as list() that maybe i am unaware of, which can achieve this as a single-liner or with the least code possible. Potentially involving interleaved explode() and implode calls and some string reversal?

推荐答案

好吧,这是一个衬里(为了便于阅读而缩进),它将返回该衬里。如果您曾经在生产中使用该功能,请不要告诉他们我已经这样做了。这是一个 3v4l

Well, here is a one liner (indented for readability's sake) that will return that. If you ever use that in production, don't tell them I did that. Here's a 3v4l

list($prev, $final) = [
    0 => array_slice(explode('.', $str), 0, -1),
    1 => array_pop(explode('.', $str))
];
var_dump($prev);
var_dump($final);







array(2) { [0]=> string(3) "all" [1]=> string(4) "your" }
string(4) "base"

这篇关于使用list()或类似方法实现左侧分配,导致除最后一个参数外的所有其他参数组成一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆