How can i take an array, divide it by two and create two lists?

前端 未结 9 1880
暗喜
暗喜 2020-12-01 10:26

Say i have an array

$array

Could anyone give me an example of how to use a foreach loop and print two lists after the initial array total

相关标签:
9条回答
  • 2020-12-01 11:07

    This Worked for me made the first array always a little longer. Thought this might help people too.

    $firsthalf = array_slice($input, 0, $len / 2 +1);
    $secondhalf = array_slice($input, $len / 2 +1);
    
    0 讨论(0)
  • 2020-12-01 11:09

    Use array_chunk to split the array up into multiple sub-arrays, and then loop over each.

    To find out how large the chunks should be to divide the array in half, use ceil(count($array) / 2).

    <?php
    $input_array = array('a', 'b', 'c', 'd', 'e', 'f');
    $arrays = array_chunk($input_array, 3);
    
    foreach ($arrays as $array_num => $array) {
      echo "Array $array_num:\n";
      foreach ($array as $item_num => $item) {
        echo "  Item $item_num: $item\n";
      }
    }
    

    Output

    Array 0:
      Item 0: a
      Item 1: b
      Item 2: c
    Array 1:
      Item 0: d
      Item 1: e
      Item 2: f
    
    0 讨论(0)
  • 2020-12-01 11:10

    this is a pagination question. you can think the pagesize=2.

    0 讨论(0)
提交回复
热议问题