Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda