0

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;
    }
}

1 Answer 1

3

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>";
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. To clarify, how would I now loop through and get the tasks and dates?
Haotian may I have your help on a another issue if possible?stackoverflow.com/questions/44877229/…

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.