Closed wpplumber closed 2 years ago
The where
method returns a sequence of elements. If you need only one element, you should use first
(if you're absolutely sure at least one element exists) or firstOrDefault
(it returns default null
if the searched sequence is empty). It also returns the whole row, not just the value, so you need to get meta_value
. So your code becomes:
$usermetas = $wpdb->get_results("SELECT * FROM {$wpdb->usermeta}");
foreach ($users as $user) {
$dateOfBirth = from($usermetas)
->firstOrDefault(function($um) {
return $um['user_id'] === $user->ID && $um['meta_key'] === 'co_dateofbirth' ;});
if ($dateOfBirth != null)
echo "co_dateofbirth value is: {$dateOfBirth->meta_value}<br/>";
}
Or, if all users are guaranteed to have a date of birth:
$usermetas = $wpdb->get_results("SELECT * FROM {$wpdb->usermeta}");
foreach ($users as $user) {
$dateOfBirth = from($usermetas)
->first(function($um) {
return $um['user_id'] === $user->ID && $um['meta_key'] === 'co_dateofbirth' ;});
echo "co_dateofbirth value is: {$dateOfBirth->meta_value}<br/>";
}
Note that your code is inefficient because it puts the whole UserMeta table into memory while you only need dates of birth. It would be more optimal modify your SQL query to get all your data at once and only it.
The following query would return only the data you actually need:
SELECT u.id, um.meta_value
FROM user AS u
INNER JOIN usermeta AS um ON um.user_id = u.id
WHERE um.meta_key = 'co_dateofbirth'
In general, if a query is possible within SQL, you should perform it within SQL. You should only use YaLinqo (and any filtering and transformation using array functions in general) only in cases SQL is unavailable.
(I haven't tested any of the code above.)
The code seems returning wrong field which is the 1st on table, is it a problem on the first function conditions!
While I'm trying to iterate through the WP users table to check meta option where ID and meta_key are the where clause conditions used in the following code: