Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value exists in JSON associative array

I have an array that looks like this:

[
    {
        "date":"2015-07-10",
        "count":"1"
    },{
        "date":"2015-07-11",
        "count":"3"
    }
]

Which is given by the following Eloquent query:

$posts = Post::select(array(
        DB::raw('DATE(`created_at`) as `date`'),
        DB::raw('COUNT(*) as `count`')
    ))
    ->where('created_at', '>', Carbon::today()->subWeek())
    ->groupBy('date')
    ->orderBy('date', 'DESC')
    ->get()
    ->toArray();

How can I check if a certain date is already in the array? I've tried the following, but it returns false (i.e. that the value isn't in the array, even though it is):

return in_array("2015-07-10", $posts);
like image 808
asd651asd Avatar asked Jul 20 '15 05:07

asd651asd


1 Answers

You can use array_column in this case.

return in_array("2015-07-10", array_column($posts, 'date'));

DOCS

like image 130
Sougata Bose Avatar answered Sep 22 '22 12:09

Sougata Bose