Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
How can I sort this array

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]
]
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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);
over 4 years ago · Santiago Trujillo Report

0

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
  ]
]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!