Pregunta

I need to grab data within array (inside array) that will grab only the second and the third rows of each line.

<?php

$salaries = array(
   //I WANT TO MAKE A NEW ARRAY FROM ALL THE SECOND AND THE THIRD ROWS 
               "a" => 2000, 1500, 3000, 1950
               "b" => 1000, 2300, 2233, 2400
               "c" => 500 , 6590, 1024, 2048
   //FOR EXAMPLE RESULTS IN THIS CASE WOULD BE :
   //$newarray = array(1500,3000,2300,2233,6590,2048);
      );

?>

If there is no direct command for that loops would be fine :)

Thanks !

¿Fue útil?

Solución

First of all, your array declaration isn't syntactically valid.

If you meant it to be a multi-dimensionl array as follows:

$salaries = array(
   "a" => array(2000, 1500, 3000, 1950),
   "b" => array(1000, 2300, 2233, 2400),
   "c" => array(500 , 6590, 1024, 2048)
);

Then, this can be done using two loops. In the first loop, loop through all the sub-arrays. Loop through the values in each sub-array, check if the value is second or third. If so, add it to the new array:

foreach ($salaries as $key => $arr) {
    for ($i=0; $i < count($arr); $i++) { 
        if ($i == 1 || $i == 2) {
            $result[$key][] = $arr[$i];
        }
    }
}

print_r($result);

Demo


For completeness, I'm going to add the solution for the case when the values are comma-separated strings, not arrays:

$salaries = array(
   "a" => '2000, 1500, 3000, 1950',
   "b" => '1000, 2300, 2233, 2400',
   "c" => '500 , 6590, 1024, 2048'
);

The logic is exactly the same, but instead of accessing the inner array elements directly, you'll have to use explode() to create an array of the values. Then use array_slice() to get the second and third elements, and create a new array from it:

$result = array();

foreach ($salaries as $key => $value) {
    $pieces = explode(', ', $value);
    $slice[$key] = array_slice($pieces, 1, 2);
    $result = array_merge($result, $slice);
}

Demo

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top