Im some new in PHP and I want to join values according to drug
key with the same id
.
My array:
Array ( [0] => Array ( [id] => 17 [drug] => Clobazam ) [1] => Array ( [id] => 23 [drug] => Dexametasona ) [2] => Array ( [id] => 23 [drug] => Diiodohidroxiquinoleína ) [3] => Array ( [id] => 25 [drug] => Diclofenac,dietilamina )
Expected output:
Array ( [0] => Array ( [id] => 17 [drug] => Clobazam ) [1] => Array ( [id] => 23 [drug] => Dexametasona, Diiodohidroxiquinoleína ) [2] => Array ( [id] => 25 [drug] => Diclofenac,dietilamina )
Advertisement
Answer
$array = [ [ 'id' => 17, 'drug' => 'Clobazam' ], [ 'id' => 23, 'drug' => 'Dexametasona' ], [ 'id' => 23, 'drug' => 'Diiodohidroxiquinoleína' ], [ 'id' => 25, 'drug' => 'Clobazam' ] ]; $result = []; foreach ($array as $item) { $id = $item['id']; $drug = $item['drug']; if (isset($result[$id])) { $result[$id]['drug'] .= ', ' . $drug; } else { $result[$id] = $item; } } $result = array_values($result); var_dump($result);