1

I'm grouping one multidimensional array by age.

This is my code:

$mEmployees = array (
    array("name"=>"Pedro",  "age"=>20, "ID"=>1111), 
    array("name"=>"Carlos", "age"=>15, "ID"=>2222), 
    array("name"=>"Susana", "age"=>20, "ID"=>3333), 
    array("name"=>"Carmen", "age"=>19, "ID"=>4444)
);
$byAge=array();


foreach ($mEmployees as $k => $oneItem) {
   $byAge[$oneItem['age']][$k] = $oneItem;
}
var_dump($byAge);

That works fine as you can see below:

output:

array(3) {
  [20]=>
  array(2) {
    [0]=>
    array(3) {
      ["name"]=>
      string(5) "Pedro"
      ["age"]=>
      int(20)
      ["ID"]=>
      int(1111)
    }
    [2]=>
    array(3) {
      ["name"]=>
      string(6) "Susana"
      ["age"]=>
      int(20)
      ["ID"]=>
      int(3333)
    }
  }
  [15]=>
  array(1) {
    [1]=>
    array(3) {
      ["name"]=>
      string(6) "Carlos"
      ["age"]=>
      int(15)
      ["ID"]=>
      int(2222)
    }
  }
  [19]=>
  array(1) {
    [3]=>
    array(3) {
      ["name"]=>
      string(6) "Carmen"
      ["age"]=>
      int(19)
      ["ID"]=>
      int(4444)
    }
  }
}

But in the results, the age key is redundant. I want to remove this key in the $byAge array.

I tried with array_slice, but it's not possible to indicate one irregular offset (the key age is in middle).

How I can achieve this easily for this result?

array(3) {
  [20]=>
  array(2) {
    [0]=>
    array(3) {
      ["name"]=>
      string(5) "Pedro"
      ["ID"]=>
      int(1111)
    }
    [2]=>
    array(3) {
      ["name"]=>
      string(6) "Susana"
      ["ID"]=>
      int(3333)
    }
  }
  [15]=>
  array(1) {
    [1]=>
    array(3) {
      ["name"]=>
      string(6) "Carlos"
      ["ID"]=>
      int(2222)
    }
  }
  [19]=>
  array(1) {
    [3]=>
    array(3) {
      ["name"]=>
      string(6) "Carmen"
      ["ID"]=>
      int(4444)
    }
  }
}

1 Answer 1

4

Cache the age value in a variable and unset from $oneItem.

foreach ($mEmployees as $k => $oneItem) {
   $age = $oneItem['age'];
   unset($oneItem['age']);
   $byAge[$age][$k] = $oneItem;
}

Demo: https://3v4l.org/pDDn5

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.