PHP使数组从键/位置开始 [英] PHP make array start from key / position

查看:115
本文介绍了PHP使数组从键/位置开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想告诉我的数组从键位置2开始,然后遍历整个数组,包括键位置2之前的值。我只想使用一个数组并指定要从其开始循环的键位置。例如,在这里我正在使用array_splice,但是它没有实现我想要的功能,请您能帮我吗?

I want to tell my array to start from key position 2 and then loop through the entire array, including the values before key position 2. I just want to use one array and specify the key position I start looping from. For example, here I am using array_splice, but it does not do what I want it to, could you help me please?

$names = array('Bill', 'Ben', 'Bert', 'Ernie');
foreach(array_slice($names, 2) as $name){
   echo $name;
}

foreach(array_slice($names, 3) as $name){
   echo $name;
}


推荐答案

如果键无关紧要,您可以将数组拼接两次,然后合并生成的数组,如下所示:

If the keys are irrelevant, you can splice the array twice, and merge the resulting arrays, like this:

$names = array('Bill', 'Ben', 'Bert', 'Ernie');
$start = 2;

foreach( array_merge( array_slice($names, $start), array_slice( $names, 0, $start)) as $name){
   echo $name;
}

您可以从演示示例

BertErnieBillBen

或者,为了提高效率,您可以使用两个循环来回绕,这会更有效

Alternatively, for efficiency, you can use two loops that are aware of wrapping around to the beginning, which will be more efficient since you are operating on the original array and not creating copies of it.

$start = 2;
for( $i = $start, $count = count( $names); $i < $count; $i++) {
    echo $names[$i];
}
$i = 0;
while( $i < $start) { 
    echo $names[$i++];
}

您也可以将其变成一个循环,并封装用于在中换为

You could also turn this into one single loop, and just encapsulate the logic for wrapping around inside the for.

这篇关于PHP使数组从键/位置开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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