如何循环获取唯一值的JSON数组[PHP]

时间:2017-01-31 12:01:23

标签: php arrays json foreach

我正在尝试循环一个JSON数组,返回一个唯一的日期以及与该日期相关的所有任务。

这是我的JSON数组的一个例子:

<!-- 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"
       }
    ]

我想要显示如下内容:

    Today 
    Clean my teeth
    Call Mom

    Tomorrow
    Jumping Jacks

    2017/03/01
    Clean The House

这是我的功能:我可以获得所有独特的日子,但我不知道如何显示与当天相关的任务。

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 个答案:

答案 0 :(得分:2)

您可以遍历JSON列表,并将唯一记录和存储任务保持在同一遍历中。

通过使用isset(),您可以确定密钥是否唯一。

试试这个:

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