简体   繁体   中英

PHP Matching value in an multi-dimensional array

I am looping between 2 times in 10 minute intervals, which works fine and outputs a time like so:

<?=$time->format('H:i')?>

I then am pulling data from the database of times I then want to see if the data in the loop matches whats coming out of the database. I have created a method to get me all the records from the database and outputs them into an array. I then wanted to use in_array to match them up then run the value through another method to get data about it. Problem is that it doesnt match up, problem being:

if (array_search($time->format('H:i'), $bookings))
echo "Match";

$booking is a multi-dimension array looking like:

Array ( 
[0] => Array ( [id] => 1 [time] => 12:00 ) 
[1] => Array ( [id] => 2 [time] => 15:00 )
...
)

Thanks in advance!

It would be much easier if you get the values directly from database. still if you want to process it in php, you can try with array_walk(). I am not sure about the syntax but should be something like

function search($value, $key, $needle)
{
    array_search($needle, $value);
}

array_walk($bookings, 'search', $time->format('H:i'));

where $value will be your inner arrays.
Guys, please correct me if i am wrong with the syntax

It would probably be simpler to directly query the database accordingly - if you can - and than your query would be something like

select * from `table_name` WHERE `date_field` = $your_date

If that does not form a solution you can use array_walk as above or simply loop a little more:

foreach($bookings as $array) {
    if(array_search($time->format('H:i'), $array)) {
        echo 'match';
        // If you don't want to keep searching use 'break'.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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