Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. <?php
  2. $a = Array(
  3. Array
  4. (
  5. "id" => 1,
  6. "id_categorie" => 1,
  7. "nb" => 18
  8. ),
  9. Array
  10. (
  11. "id" => 1,
  12. "id_categorie" => 8,
  13. "nb" => 14
  14. ),
  15. Array
  16. (
  17. "id" => 2,
  18. "id_categorie" => 10,
  19. "nb" => 15
  20. )
  21.  
  22. );
  23. $result = array();
  24.  
  25. foreach ($a as $k=>$v){
  26.  
  27. $result[$v['id']] =$v;
  28.  
  29.  
  30. }
  31.  
  32. echo '<pre>';
  33. print_r($result);
  34. echo '</pre>';
  35. ?>
  36.  
  37. Array
  38. (
  39. [1] => Array
  40. (
  41. [id] => 1
  42. [id_categorie] => 8
  43. [nb] => 14
  44. )
  45.  
  46. [2] => Array
  47. (
  48. [id] => 2
  49. [id_categorie] => 10
  50. [nb] => 15
  51. )
  52.  
  53. )
  54.  
  55. Array
  56. (
  57. [1] => Array
  58. (
  59. Array
  60. (
  61. "id_categorie" => 1,
  62. "nb" => 18
  63. ),
  64. Array
  65. (
  66. "id_categorie" => 8,
  67. "nb" => 14
  68. )
  69. )
  70.  
  71. [2] => Array
  72. (
  73. [id_categorie] => 10
  74. [nb] => 15
  75. )
  76.  
  77. )
  78.  
  79. $result = array();
  80. foreach ($a as $arr) {
  81. // unset the 'id' index; it becomes the array's index instead
  82. $id = $arr['id'];
  83. unset($arr['id']);
  84. if (!isset($result[$id])) {
  85. // add the new item as a top-level element
  86. $result[$id] = $arr;
  87. } else if (isset($result[$id]['id_categorie'])) {
  88. // the current 'id' is set as a top-level element; convert it
  89. // into a sub-array and also add the new element to it
  90. $new = array($result[$id], $arr);
  91. $result[$id] = $new;
  92. } else {
  93. // we already have a sub-array of items; add the new element
  94. $result[$id][] = $arr;
  95. }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement