我应该如何将我的数据与数组json进行比较

时间:2017-05-17 06:11:03

标签: php arrays json

  

我很难将天与数组进行比较

     

这是我的阵列:

array:2 [
0 => {
  "id": 1
  "time_in": "08:00:00"
  "time_out": "17:00:00"
  "days": "["tuesday","thursday","saturday"]"
}
1 => {
  "id": 2
  "time_in": "09:00:00"
  "time_out": "18:00:00"
  "days": "["monday","wednesday","friday"]"
}
  ]
  

注意:天数是来自数据库的json数据

     

我有这个变量日

$day = 'friday';
  

我只想用'星期五'来获取数组数据。在他们的日子里   请帮助我解决我的代码我不知道应该如何操纵它   或者我将使用什么代码来获取它

我希望有这个输出:

$day = 'friday';

1 => {
      "id": 2
      "time_in": "09:00:00"
      "time_out": "18:00:00"
      "days": "["monday","wednesday","friday"]"
    }
  

因为它当天有星期五

4 个答案:

答案 0 :(得分:1)

您可以使用 in_array()函数,该函数在数组中搜索特定值。

搜索 $ day ="周五" ,我将另一个数组声明为 $ b 并将过滤值添加到其中。

试试这个:

$array = array(array("id"=>"1","time_in"=>"08:00:00","time_out"=>"17:00:00","days"=>'["tuesday","thursday","saturday"]'),
array("id"=>"2","time_in"=>"09:00:00","time_out"=>"18:00:00","days"=>'["monday","wednesday","friday"]'));
      $day = "friday";
      $b = array();
      foreach ($array as $val) {
           if (in_array($day,$val['days'])) {
               $b[] = $val;
           }
       }

    print_r($b);

答案 1 :(得分:0)

使用in_array查找数组

中的数据
foreach($your_array as $obj){
   if(in_array($day, $obj->days)){
      return $obj;
   }
}

答案 2 :(得分:0)

让我们说您的JSON数据定义为$json

$json_array = json_decode($json);

$result = [];

foreach($json_array as $arr){
    if(in_array($day,$arr->days)){
        $result[] = $arr;
    }
}

答案 3 :(得分:0)

<?php

// the day you want
$day = 'friday';

// decode json to php array
$days = json_decode($yourJSONArrayFromDatabase, true);

for ($i=0; $i < count($days); $i++)
{
    if (in_array($day, $days[$i]['days'])) {
        echo json_encode($days[$i]);
        break;
    }
}