Search code examples
phparraysmultidimensional-arraykeymultiple-value

Check if value exists in php multi-dimensional array before adding


I have a separate set of functions that grabs a "Date" and a "Time" from my application and puts the date into as a key, and the time as a multi-dimensional value.

For example purposes:

$alldatetimes = array(
    'date1' => array('13:00','14:30','14:30','14:30','15:00'),
    'date2' => array('09:00','10:00','10:30','10:30','12:00')
    );

foreach ($alldatetimes as $date => $times) {
echo '<h1>This Exports:</h1>';  
echo '<h2>'.$date.'</h2><br>';
    foreach ($times as $time) {

        echo $time.'<br>';
    }
}

This exports:
date1
13:00
14:30
14:30
14:30
15:00

date2
09:00
10:00
10:30
10:30
12:00

I'm trying to control if the time is put into the array so only one value each is in the array (I don't want 3 instances of 14:30 for that date).

Based on other posts here I tried to build something like this to identify if the value was there, but I can't figure out how to tie it all together:

function searchForId($id, $array) {
    foreach ($array as $date => $times) {
        foreach ($times as $time) { 
            if ($time === $id) {
                return $time;
            }
        }
    }
    return null;
}

Any ideas?

Update: Here is how the array is initially being created - this probably can be more efficient:

while ($schedule_q -> have_posts() ) : $schedule_q->the_post();
    $alldatetimes [get_the_date()][] = get_the_time();  
endwhile;

Solution

  • It is not shown in your question, but how about modifying your function that builds the date/time array to use the times as keys instead of values? Using something like

    $alldatetimes[$date][$time]++
    

    in that function would give you an array with one value for each time that would be the number of occurrences of that date/time combination, like this:

    $alldatetimes = array(
        'date1' => array('13:00' => 1,'14:30' => 3,'15:00' => 1),
        'date2' => array('09:00' => 1,'10:00' => 1,'10:30' => 2,'12:00' => 1)
        );
    

    Then you could change your code that prints them out to use the key.

    foreach ($times as $time => $count) {
        echo $time.'<br>';
    }