1

How is it possible to generate an array of array of objects where they are grouped based on the object property 'name'? I can do this in Javascript but not sure how to accomplish this in PHP.

Here is an example snippet of the current json_encoded echo output:

[
    {"id":14970,
    "amount":"70",
    "name":"Food"
    },
    {"id":14970,
    "amount":"100",
    "name":"Drink"
    },
    {"id":14970,
    "amount":"100",
    "name":"Food"
    },
    {"id":14970,
    "amount":"300",
    "name":"Drink"
    },
    {"id":14970,
    "amount":"10",
    "name":"Taxi"
    },
    {"id":14970,
    "amount":"200",
    "name":"Food"
    }
]

Here would be the desired output:

[
    [
        {"id":14970,
        "amount":"70",
        "name":"Food"
        },
        {"id":14970,
        "amount":"100",
        "name":"Food"
        },
        {"id":14970,
        "amount":"200",
        "name":"Food"
        }
    ],
    [
        {"id":14970,
        "amount":"100",
        "name":"Drink"
        },
        {"id":14970,
        "amount":"300",
        "name":"Drink"
        }
    ],
    [
        {"id":14970,
        "amount":"10",
        "name":"Taxi"
        }
    ]
]

Would be very grateful if the solution is explained as my knowledge on PHP is limited and would love to learn how this works for future reference and usage of PHP.

1
  • have you tried anything so far? Commented Oct 1, 2018 at 5:14

4 Answers 4

1

Use the name in the array as the group (key) of a multi-dimensional array.

$array = json_decode('[
{"id":14970,
"amount":"70",
"name":"Food"
},
{"id":14970,
"amount":"100",
"name":"Drink"
},
{"id":14970,
"amount":"100",
"name":"Food"
},
{"id":14970,
"amount":"300",
"name":"Drink"
},
{"id":14970,
"amount":"10",
"name":"Taxi"
},
{"id":14970,
"amount":"200",
"name":"Food"
}
]',true);

$result = [];
foreach($array as $key=>$value){
    $group = $value['name'];
    if(!isset($result[$group])) $result[$group ] = [];

    $result[$group][] = $value;
}

//remove the top level keys, it's easier to build it with them
$result = array_values($result); 

Output

 array (
  0 => 
  array (
    0 => 
    array (
      'id' => 14970,
      'amount' => '70',
      'name' => 'Food',
    ),
    1 => 
    array (
      'id' => 14970,
      'amount' => '100',
      'name' => 'Food',
    ),
    2 => 
    array (
      'id' => 14970,
      'amount' => '200',
      'name' => 'Food',
    ),
  ),
  1 => 
  array (
    0 => 
    array (
      'id' => 14970,
      'amount' => '100',
      'name' => 'Drink',
    ),
    1 => 
    array (
      'id' => 14970,
      'amount' => '300',
      'name' => 'Drink',
    ),
  ),
  2 => 
  array (
    0 => 
    array (
      'id' => 14970,
      'amount' => '10',
      'name' => 'Taxi',
    ),
  ),
)

Sandbox

Then you just need to json_encode it.

 $result = [];
 foreach($array as $key=>$value){
     $group = $value['name'];
     if(!isset($result[$group])) $result[$group ] = [];

     $result[$group][] = $value;
 }

 echo json_encode(array_keys($result), JSON_PRETTY_PRINT);

Which gives:

[
    [
        {
            "id": 14970,
            "amount": "70",
            "name": "Food"
        },
        {
            "id": 14970,
            "amount": "100",
            "name": "Food"
        },
        {
            "id": 14970,
            "amount": "200",
            "name": "Food"
        }
    ],
    [
        {
            "id": 14970,
            "amount": "100",
            "name": "Drink"
        },
        {
            "id": 14970,
            "amount": "300",
            "name": "Drink"
        }
    ],
    [
        {
            "id": 14970,
            "amount": "10",
            "name": "Taxi"
        }
    ]
]

Sandbox

Sign up to request clarification or add additional context in comments.

2 Comments

This is fantastic. Thank you very much.
Sure it was pretty simple, basic stuff.
1
<?php
$array = json_decode('[
    {"id":14970,
    "amount":"70",
    "name":"Food"
    },
    {"id":14970,
    "amount":"100",
    "name":"Drink"
    },
    {"id":14970,
    "amount":"100",
    "name":"Food"
    },
    {"id":14970,
    "amount":"300",
    "name":"Drink"
    },
    {"id":14970,
    "amount":"10",
    "name":"Taxi"
    },
    {"id":14970,
    "amount":"200",
    "name":"Food"
    }
]',true);

$types = [];
$splited = [];

foreach($array as $key => $value){
    // searching types for the type
    if(in_array($value['name'],$types)){
        // adding it to splited with the correct key if type exists
        $splited[array_search($value['name'],$types)][] = $value;
    } else {
        // creating a new type if not exists
        $types[] = $value['name'];
        $splited[] = [$value];
    }
}

echo '<pre>';
var_dump($splited);
echo '</pre>';
?>

Comments

1

Above mentioned array of the object looks like JSON format. I have converted into the array and grouped it. please try this it's might be helpful to you :)

$objStr = '[
    {"id":14970,
    "amount":"70",
    "name":"Food"
    },
    {"id":14970,
    "amount":"100",
    "name":"Drink"
    },
    {"id":14970,
    "amount":"100",
    "name":"Food"
    },
    {"id":14970,
    "amount":"300",
    "name":"Drink"
    },
    {"id":14970,
    "amount":"10",
    "name":"Taxi"
    },
    {"id":14970,
    "amount":"200",
    "name":"Food"
    }
]';
$arr = json_decode($objStr,true);
$arrArr = array();
foreach($arr as $k => $arrOfArr) {
    $arrArr[$arrOfArr['name']][] = $arrOfArr;
}
echo "<pre>"; print_r($arrArr); echo "</pre>";

Comments

1
 $json_string = '[
    {"id":14970,
    "amount":"70",
    "name":"Food"
    },
    {"id":14970,
    "amount":"100",
    "name":"Drink"
    },
    {"id":14970,
    "amount":"100",
    "name":"Food"
    },
    {"id":14970,
    "amount":"300",
    "name":"Drink"
    },
    {"id":14970,
    "amount":"10",
    "name":"Taxi"
    },
    {"id":14970,
    "amount":"200",
    "name":"Food"
    }
]';
        $array = json_decode($json_string, true);
        $result = array();
        if (count($array) > 0) {
            foreach ($array as $value) {
                $name = $value['name'];

                $result[$name][] = $value;
            }
        }
        echo '<pre>';
        print_r(array_values($result));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.