user3053151
user3053151

Reputation: 137

How to loop through an JSON array getting unique values [PHP]

I am trying to loop through a JSON Array returning a unique date and all the tasks associated with that date.

This is an example of my JSON array:

<!-- language: lang-json -->

    [
       {
          "task":"Clean my teeth",
          "date":"today"
       },
       {
          "task":"Jumping Jacks",
          "date":"tomorrow"
       },
       {
          "task":"Call Mom",
          "date":"today"
       },
       {
          "task":"Wash The Dog",
          "date":"2017/03/01"
       },
       {
          "task":"Clean The House",
          "date":"today"
       }
    ]

I want to display something like this:

    Today 
    Clean my teeth
    Call Mom

    Tomorrow
    Jumping Jacks

    2017/03/01
    Clean The House

Here is my function: I can get all the unique days but I'm not sure how to display the tasks associated with that day.

public static function Iteration()
{
    $file = file_get_contents("newfile.php");
    $result = rtrim( $file, ",");          
    $array = json_decode('[' . $result . ']');

    $unique_dates = array();
    $unique_tasks = array();

    foreach($array as $item) { 
        if ( in_array($item->date, $unique_dates) ) {
            continue;
        }

        $unique_dates[] = $item->date;
        $time = strtotime($item->date);
        $newformat = date('Y-m-d',$time);    
        echo '<h2>' . $newformat . '</h2>';
        echo $item->task;
    }
}

Upvotes: 0

Views: 2609

Answers (1)

Haotian Liu
Haotian Liu

Reputation: 886

You can traverse the JSON list, and keep the unique records and store tasks at the same traversal.

By using the isset(), you can determine whether the key is unique or not.

Try this:

<?php
$json = '[{"task": "Clean my teeth","date": "today"},{"task": "Jumping Jacks","date": "tomorrow"},{"task": "Call Mom","date": "today"},{"task": "Wash The Dog","date": "2017/03/01"},{"task": "Clean The House","date": "today"}]';

$array = json_decode($json);
$res = array();
foreach ($array as $each) {
    if (isset($res[$each->date]))
        array_push($res[$each->date], $each->task);
    else
        $res[$each->date] = array($each->task);
}

foreach ($res as $date => $tasks){
    echo "<h3>{$date}</h3>";
    foreach ($tasks as $task)
        echo "<p>$task</p>";
}

Upvotes: 3

Related Questions