John Davidson

php - group an array by name and age

0 comments
Message:


can you help me please, I have this PHP from which I get an array. But I want to change its output and be able to group them by name and age.


This is my PHP


<?php

$name = array();
$age = array();

$sql = $conn->runQuery("SELECT * FROM staff");
$sql->execute();

while ($row = $sql->fetch(PDO::FETCH_ASSOC))
{
$name[] = $row['name'];
$age[] = $row['age'];
}

$posts = [
"name" => $name,
"age" => $age,
];

echo json_encode($posts, JSON_PRETTY_PRINT);

?>

this is the result.


{
"name": [
"Erik",
"Rose",
"Abby",
"Abner"
],
"age": [
"18",
"28",
"25",
"22"
]
}

But, I would like the array to return as follows.


[
{
"name": Erik,
"age": 18
},
{
"name": Rose,
"age": 28
}
]

Can you help me please, how do I have to make this kind of array?



My Answer:
php
$data = array(
array('name' => 'John', 'age' => 25),
array('name' => 'Jane', 'age' => 30),
array('name' => 'John', 'age' => 25),
array('name' => 'Jane', 'age' => 35),
array('name' => 'John', 'age' => 30)
);

$groupedData = array();

foreach ($data as $item) {
$name = $item['name'];
$age = $item['age'];

if (!isset($groupedData[$name])) {
$groupedData[$name] = array();
}

if (!isset($groupedData[$name][$age])) {
$groupedData[$name][$age] = 1;
} else {
$groupedData[$name][$age]++;
}
}

print_r($groupedData);


This code will group the array by name and age, and the output will show the count of each combination of name and age.

Rate this post

3 of 5 based on 8040 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us