Comum
Comum

Reputation: 453

Search for a specific value in an Associative array

I have an associative array that is created by a query using the following code:

$query = ("SELECT `time_stamp`, `EAE` FROM `table`");
$stmt = $con->query($query);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;

To access each value I usually use a for loop such as:

for($i = 0 ; $i < count($rows) ; $i++)
{
     echo $rows[$i]['time_stamp'].' '.$rows[$i]['EAE'].'<br>';
}

However, I want to access a value that is registered in a specific time_stamp. To do so I am having trouble using the function array_search. I've tried setting it up like this:

$sum_a = array_search(date('Y-m-d', $rows[$j]['time_stamp'])." 00:00:00", $rows);

But it doesn't find anything. I can't find a way to use this function with a double scope array. Do you guys know how I can use it? Or if there is another way that doesn't involve accessing the database again or running a loop on the whole array?

PS:I've also tried to detect a value using in_array but it didn't find anything.

Upvotes: 0

Views: 62

Answers (1)

mleko
mleko

Reputation: 12233

$rows in your case will be multidimensional array. array_search loops only first dimension - thats why your code is not working.

You can get values of specified column using.

$column = array_map(function($element){return $element['time_stamp'];}, $rows);

For PHP 5.5+ you can use array_column.

And then you can use own code

$sum_a = array_search(date('Y-m-d', $rows[$j]['time_stamp'])." 00:00:00", $column);

Upvotes: 2

Related Questions