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);
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);
}