简体   繁体   English

如何遍历JSON数组以获取唯一值[PHP]

[英]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. 我试图遍历一个JSON数组,返回一个唯一的日期以及与此日期相关的所有任务。

This is an example of my JSON array: 这是我的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"
       }
    ]

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

You can traverse the JSON list, and keep the unique records and store tasks at the same traversal. 您可以遍历JSON列表,并保持唯一记录和存储任务的遍历相同。

By using the isset() , you can determine whether the key is unique or not. 通过使用isset() ,可以确定密钥是否唯一。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM