Selecting multiple array elements

这一生的挚爱 提交于 2021-02-05 09:12:09

问题


Is there a way in PHP to select multiple array elements at once, e.g. such that in a for loop, $i = size of first set to be selected, and then subsequent increments represent selecting the next set of that size, from an array - ?

Thanks!


回答1:


I.e. instead of just looping through one array element at a time, but to loop through selected pairs instead (e.g. 3 elements, and then to do something to those 3).

there are many ways to do it.
one would be

$arr = array(1,2,3,4,5,6,7,8,9);
$new = array_chunk($arr,3);
foreach ($new as $chunk) {
  print_r($chunk);// 3 elements to do something with
}



回答2:


It depends on how you want to group your elements.

$i = 4;
$source = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 );
// If you want consecutive elements in the same group, i.e. the first $i elements etc
$chunks = array_chunk( $source, $i );
foreach( $chunks as $chunk )
{
    // Iterate over chunk
    echo '---<br />';
    foreach( $chunk as $element )
    {
        echo $element . '<br />';
    }
}
echo '---<br />';
echo '---<br />';
// Otherwise if you want consecutive elements in separate groups
$lastElement = count( $source ) - 1;
$step = ceil( count( $source) / $i );
for( $offset = 0; $offset < $step; $offset++ )
{
    echo '---<br />';
    for( $element = $offset; $element <= $lastElement; $element+= $step )
    {
        echo $source[$element] . '<br />';
    }
}
echo '---<br />';



回答3:


If I understand your question right you have something like this?

$array = array( "A" => array("a","b"),
                "B" => array("a","b"),
                "C" => array("a","b"));

and you want to loop thought A, B, C at the same same time?

Then you can do something like this;

for($i=0;$i<=max(count($array['A']),count($array['B']),count($array['B']))){
     if(count($array['A'])<=$i+1) {
         echo $array['A'][$i];
     }
     if(count($array['B'])<=$i+1) {
         echo $array['B'][$i];
     }
     if(count($array['B'])<=$i+1) {
         echo $array['B'][$i];
     }
     $i++;
}


来源:https://stackoverflow.com/questions/9453040/selecting-multiple-array-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!