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

251
Vistas
php loop over multidimensional array can combine same key/value into new array element

I am getting some data out of mysql into an array like this

array(
    [0] = array(
        'code' => '123456',
        'title' => 'something',
        'price' => '2.00',
        'other_value' => '555555'
    ),
    [1] = array(
        'code' => '123456',
        'title' => 'something',
        'price' => '2.00',
        'other_value' => '666666'
    ),
    [2] = array(
        'code' => '234567',
        'title' => 'something else',
        'price' => '3.00',
        'other_value' => '333333'
    ),
    [3] = array(
        'code' => '345678',
        'title' => 'another thing',
        'price' => '4.00',
        'other_value' => NULL
    ),
)

what i need to do is for each row, if the key code appears more than once, merge the rows into one but create a new array for the other_value like so

array(
    [0] = array(
        'code' => '123456',
        'title' => 'something',
        'price' => '2.00',
        'other_value' => array(
            [0] => '555555',
            [1] => '666666'
        )
    ),
    [1] = array(
        'code' => '234567',
        'title' => 'something else',
        'price' => '3.00',
        'other_value' => '333333'
    ),
    [2] = array(
        'code' => '345678',
        'title' => 'another thing',
        'price' => '4.00',
        'other_value' => NULL
    ),
)

What is the best way to achieve this?

I did think about looping over the each row and checking for existence of thtat key/value then do something if it exists.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

@AdRock i hope you want to merge array in case of when 'code' will be same, if this is so then try below one:

<?php
$arr = array(
            array(
                'code' => '123456',
                'title' => 'something',
                'price' => '2.00',
                'other_value' => '555555'
            ),
            array(
                'code' => '123456',
                'title' => 'something',
                'price' => '2.00',
                'other_value' => '666666'
            ),
           array(
                'code' => '234567',
                'title' => 'something else',
                'price' => '3.00',
                'other_value' => '333333'
            ),
            array(
                'code' => '345678',
                'title' => 'another thing',
                'price' => '4.00',
                'other_value' => NULL
            )
        );
echo "<pre>";
print_r($arr);// array before
$isExist = array();
foreach($arr as $key => $value){
    if(in_array($value["code"], $isExist)){
        $getKey = array_search($value["code"], $isExist);
        $arr[$getKey]["other_value"] = array($arr[$getKey]["other_value"], $value["other_value"]);
        unset($arr[$key]);
    }
    else{
        $arr[$key] = $value;
    }
    $isExist[$key] = $value["code"];
}
echo "<pre>";
print_r(array_values($arr));// array after
?> 
over 4 years ago · Santiago Trujillo Denunciar

0

The approach that I would suggest is to loop through the array and store the value of code into a new array and store the entire result set into a new array. With each iteration, check whether the value is present or not in the code value stored array. And if value found then in that case, get the key of the code array and use the same key for the result array and store it inside the other_value. Hope it makes sense.

over 4 years ago · Santiago Trujillo Denunciar

0

Looping over the array and creating a new array using the 'code' values as keys might be the simplest method. In that case you can check if the key allready exists.

$new_array=array();

foreach($array as $part){
  $code_as_key = $part['code'];
  //if code allready in the new array, just add a new value
  if( isset($new_array[$code_as_key]) ){
     $new_array[$code_as_key]['other_value'][] = $part['other_value'];
     }
  //else add the new code
  else{
     $new_array[$code_as_key]=$part;
     }
}
//re-index the new array, starting from key 0
$new_array=array_values($new_array);
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