This article describes the PHP method of reorganizing a two-dimensional array of MySQL duplicate ID into a three-dimensional array. Share it for your reference, as follows:
Application scenarios
When MYSQL uses association query, for example, product table is associated with product picture table, and multiple product pictures of a product, the association query results are as follows:
$arr=[ ['id'=>1,'img'=>'img1'], ['id'=>1,'img'=>'img2'], ['id'=>1,'img'=>'img3'], ['id'=>2,'img'=>'img1'], ['id'=>2,'img'=>'img2'], ['id'=>2,'img'=>'img3'], ['id'=>3,'img'=>'img1'], ['id'=>3,'img'=>'img2'], ['id'=>3,'img'=>'img3'], ]
Then, the result we want is generally like this, as follows:
$arr=[ ['id'=>1,'img'=>['img1','img2','img3']], ['id'=>2,'img'=>['img1','img2','img3']], ['id'=>3,'img'=>['img1','img2','img3']], ]
Solution
$arr=[ ['id'=>1,'img'=>'img1'], ['id'=>1,'img'=>'img2'], ['id'=>1,'img'=>'img3'], ['id'=>2,'img'=>'img1'], ['id'=>2,'img'=>'img2'], ['id'=>2,'img'=>'img3'], ['id'=>3,'img'=>'img1'], ['id'=>3,'img'=>'img2'], ['id'=>3,'img'=>'img3'], ] $arr1=array(); foreach ($arr as $key => $value) { if( in_array($value['id'], $value)){ $arr1[$value['id']]['id']=$value['id']; $arr1[$value['id']]['img'][]=$value['img']; } } var_dump($arr1);
For more information about PHP related content, please check out the topic of this site:Complete collection of PHP array (Array) operation techniques》、《Summary of php sorting algorithm》、《Summary of common traversal algorithms and techniques for PHP》、《PHP data structure and algorithm tutorial》、《Summary of PHP Programming Algorithm》、《Summary of PHP mathematical operation skills》、《Summary of usage of php regular expressions》、《Summary of PHP operations and operator usage》、《Summary of usage of php strings"and"Summary of common database operation techniques for php》
I hope this article will be helpful to everyone's PHP programming.