Home > Blockchain >  How can I sort this array
How can I sort this array

Time:03-11

I got an array like this.

array:3 [▼
  0 => array:2 [▼
    "id" => "1039"
    "total" => 2.3
  ]
  1 => array:2 [▼
    "id" => "1039"
    "total" => -3.0
  ]
  2 => array:2 [▼
    "id" => "10007"
    "total" => 15.5
  ]
]

I need "total" for same "id" in the same array. e.g For "id" = 1039 array should be

[2.3, -3.0]

For "id" = 10007 array should be

[15.5]

My desired array is

[
  [2.3, -3.0],
  [15.5]
]

CodePudding user response:

You can loop over your array and set it to the another array like this:

$array = [
    ['id' => 1, 'value' => 2],
    ['id' => 1, 'value' => 3],
    ['id' => 2, 'value' => 5],
];

$temp = [];

foreach($array as $element){
    if(!isset($temp[$element['id']])){
        $temp[$element['id']] = [];
    }
    
    $temp[$element['id']][] = $element['value'];
}


var_dump($temp);

CodePudding user response:

You really want them keyed by the arrays ID.

$arr = [ ["id" => "1039", "total" => 2.3],["id" => "1039","total" => -3.0],["id" => "10007","total" => 15.5]];

$total = [];
foreach($arr as $item) {
    $total[$item['id']][] = $item['total'];
}

That will return

array:2 [
  1039 => array:2 [
    0 => 2.3
    1 => -3.0
  ]
  10007 => array:1 [
    0 => 15.5
  ]
]
  • Related