views:

39

answers:

3

I have an array in php like this :

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
       )

) 

How do I get the 1st-5th rows of sub-array for each array, like this :

Result :

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  A: 
$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, 5);
}

The $sliced_array will then contain the output you wanted.

zeroFiG
Whoa, it's solved my problem. Thanks!
Apocalypshiit
No problem! Glad to help
zeroFiG
+3  A: 
  • Iterate over the array.
  • Read the value by reference.
  • Delete key-values from offset 5 till the end. You need not collect the return value because we are using the reference to the original array.

.

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

Working ideone link

codaddict
A: 

You might want to look into the php function array_splice.

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

Thomas
You might want to look into the question's title.
Ruel
I see your point, but why would he ask that question if he already knew about that function? The first line of the link I gave says "array_slice — Extract a slice of the array"? but yes, I will pay closer attention to the title when answering future questions =D
Thomas