Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $a = Array(
- Array
- (
- "id" => 1,
- "id_categorie" => 1,
- "nb" => 18
- ),
- Array
- (
- "id" => 1,
- "id_categorie" => 8,
- "nb" => 14
- ),
- Array
- (
- "id" => 2,
- "id_categorie" => 10,
- "nb" => 15
- )
- );
- $result = array();
- foreach ($a as $k=>$v){
- $result[$v['id']] =$v;
- }
- echo '<pre>';
- print_r($result);
- echo '</pre>';
- ?>
- Array
- (
- [1] => Array
- (
- [id] => 1
- [id_categorie] => 8
- [nb] => 14
- )
- [2] => Array
- (
- [id] => 2
- [id_categorie] => 10
- [nb] => 15
- )
- )
- Array
- (
- [1] => Array
- (
- Array
- (
- "id_categorie" => 1,
- "nb" => 18
- ),
- Array
- (
- "id_categorie" => 8,
- "nb" => 14
- )
- )
- [2] => Array
- (
- [id_categorie] => 10
- [nb] => 15
- )
- )
- $result = array();
- foreach ($a as $arr) {
- // unset the 'id' index; it becomes the array's index instead
- $id = $arr['id'];
- unset($arr['id']);
- if (!isset($result[$id])) {
- // add the new item as a top-level element
- $result[$id] = $arr;
- } else if (isset($result[$id]['id_categorie'])) {
- // the current 'id' is set as a top-level element; convert it
- // into a sub-array and also add the new element to it
- $new = array($result[$id], $arr);
- $result[$id] = $new;
- } else {
- // we already have a sub-array of items; add the new element
- $result[$id][] = $arr;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement