Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

252
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda