Search code examples
phparraysmultidimensional-arraygroupingsub-array

Group rows of a 2d array by a column and create a subarray from another column within each group


I use php glob function for get images in sub directories and I dont know how many files exist in each directory

directory name is id and I want to categorize all images in directories in one array

$arr = [];
$dir = dirname(__FILE__)."/gulets";
$files = glob($dir."/*/*_gulet_o_*");
foreach ($files as $file) {
    $fullname = str_replace($dir."/", "", $file);
    $name = explode("/", $fullname);
    $name1 = array('id'=>$name[0],'name'=>$name[1]);
    $arr[] = $name1;
}   
header('Content-Type: application/json');
echo json_encode($arr);

[
{
"id": "10",
"name": "asdsad_gulet_o_1.jpg"
},
{
"id": "10",
"name": "wqes_gulet_o_10.jpg"
},
{
"id": "10",
"name": "qwsdf_gulet_o_11.jpg"
},
{
"id": "10",
"name": "sdce_gulet_o_12.jpg"
},
{
"id": "11",
"name": "fsdsc_gulet_o_13.jpg"
},
{
"id": "11",
"name": "drfvc_gulet_o_14.jpg"
},
{
"id": "12",
"name": "dsyjhk_gulet_o_15.jpg"
},
.
.

and I need change it like this :

    [
    {
    "id": "10",
    "name1": "asdsad_gulet_o_1.jpg",
    "name2": "wqes_gulet_o_10.jpg",
    "name3": "qwsdf_gulet_o_11.jpg"
    "name4": "sdce_gulet_o_12.jpg"
    },
    {
    "id": "11",
    "name1": "fsdsc_gulet_o_13.jpg"
    "name2": "drfvc_gulet_o_14.jpg"
    },
    {
    "id": "12",
    "name1": "dsyjhk_gulet_o_15.jpg"
.
.

Solution

  • I think creating indexes like name1, name2, name3 etc is not useful. You should create subarray with index names and there put your names. Try code like this:

    <?php
    
    $array = array(
        array('id'=>1, 'name'=>'qwerty'),
        array('id'=>2, 'name'=>'asdf'),
        array('id'=>2, 'name'=>'hjkl'),
        array('id'=>1, 'name'=>'cvbnm'),
        array('id'=>1, 'name'=>'yuiop'),
    );
    
    $groups = array();
    
    foreach($array as $singleRow)
    {
        if(!isset($groups[$singleRow['id']]))
            $groups[$singleRow['id']] = array('id'=>$singleRow['id'], 'names'=>array());
    
        $groups[$singleRow['id']]['names'][] = $singleRow['name'];
    }
    $json = json_encode(array_values($groups));     
    var_dump($json);
    

    It outputs:

    [{"id":1,"names":["qwerty","cvbnm","yuiop"]},{"id":2,"names":["asdf","hjkl"]}]