0

I'm new to PHP and I am reading data from external JSON file using PHP and I would like to group the same value (similar to Group by in MySQL). I have tried several ways and research but I could not get the expected result please help.

This is my JSON data:

[{"name":"jonh","school":"Barak Primary school","class":"3rd grade","year":"2019"},{"name":"Danny","school":"Barak Primary school","class":"4rd grade","year":"2019"},{"name":"Ben","school":"Mara Primary school","class":"3rd grade","year":"2019"}{"name":"West","school":"Mara Primary school","class":"3rd grade","year":"2019"}]

And this is my PHP

$json = file_get_contents('https://xxxx.json');//get data from url
$posts = json_decode($json,true); // put data into variable 
foreach ($posts as $val) {
     echo '<p>' . $val[school] . '</p>';
}

And this is result I got:

Barak Primary School
Barak Primary School
Mara Primary School
Mara Primary School

But I want the result like this:

Barak Primary School
Mara Primary School 

So in this case it grouped the same value into one, all your suggestions are appreciated.

1 Answer 1

1

You can use array_column to extract the school values from your JSON, and then array_unique to find only the distinct values. You can then loop over those values:

$schools = array_unique(array_column($posts, 'school'));
foreach ($schools as $school) {
    echo '<p>' . $school . '</p>';
}

Output:

<p>Barak Primary school</p><p>Mara Primary school</p>

Demo on 3v4l.org

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

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.