在多维数组中的array_slice?

时间:2010-10-01 07:30:27

标签: php arrays multidimensional-array

我在php中有一个像这样的数组:

Array
(
    [0] => Array
        (
              [915] => 1
              [1295] => 1
              [1090] => 1
              [1315] => 0.93759357774
              [128] => 0.93759357774
              [88] => 0.731522789561
              [1297] => 0.731522789561
              [1269] => 0.525492880722
              [1298] => 0.525492880722
              [121] => 0.519133966069
         )
   [1] => Array
       (
              [585] => 1
              [1145] => 1
              [1209] => 1
              [375] => 1
              [1144] => 1
              [913] => 1
              [1130] => 0.996351158355
              [215] => 0.937096401456
              [1296] => 0.879373313559
              [30] => 0.866473953643
              [780] => 0.866473953643
              [1305] => 0.866473953643
              [1293] => 0.866473953643
       )

) 

如何获得每个数组的第1-5行子数组,如下所示:

结果:

Array
(
    [0] => Array
        (
              [915] => 1
              [1295] => 1
              [1090] => 1
              [1315] => 0.93759357774
              [128] => 0.93759357774
         )
   [1] => Array
       (
              [585] => 1
              [1145] => 1
              [1209] => 1
              [375] => 1
              [1144] => 1
       )

)

3 个答案:

答案 0 :(得分:15)

$multid_array = array(/* Your Multidimensional array from above*/);

$sliced_array = array();  //setup the array you want with the sliced values.

//loop though each sub array and slice off the first 5 to a new multidimensional array
foreach ($multid_array as $sub_array) {
    $sliced_array[] = array_slice($sub_array, 0, 5);
}

$ sliced_array将包含您想要的输出。

答案 1 :(得分:5)

  • 迭代数组。
  • 通过引用阅读该值。
  • 从偏移5删除键值,直到 结束。您无需收集返回值,因为我们正在使用对原始数组的引用。

foreach($mainArray as $key => &$value) {
  array_splice($value,5);
}

Working ideone link

答案 2 :(得分:-1)

您可能需要查看php函数array_splice。

http://no.php.net/manual/en/function.array-slice.php