Reputation: 425
I have an associative array which looks like this:
Array (
[0] => Array ( )
[1] => Array ( )
[2] => Array ( [318] => 3.3333333333333 )
[3] => Array ( )
[4] => Array ( )
[5] => Array ( [317] => 5 )
)
I want to return all the array keys of the array as number, not string; thats why I am not echoing it. This is how I am trying:
function user_rated_posts(){
global $author;
if(isset($_GET['author_name'])) :
$curauth = get_userdatabylogin($author_name);
else :
$curauth = get_userdata(intval($author));
endif;
$user_rated_posts = get_user_meta($curauth->ID, 'plgn_rating',true);
foreach ($user_rated_posts as $arrs){
foreach($arrs as $key=> $value){
$keys= $key;
}
}
return $keys;
}
when I call the function like this:
array( explode(',',user_rated_posts()) )
I am only getting this
array(317)
I am trying to get all the keys in comma separated format, like:
array(318, 317)
Thanks.
Upvotes: 0
Views: 131
Reputation: 6202
I came up with a way that avoids the nested looping in favor of PHP's built in functions:
$result = array_map(array_keys,$user_rated_posts);
$result2 = array_map(implode, $result);
$result3 = array_filter($result2);
First line iterates over the array, returning the keys. Second line reduces the sub-array to strings. Third line removes the empty values.
Here is a working version: https://eval.in/99119
Added bonus: keeps the positions where the values were found as the keys like:
array(2) {
[2]=>
string(3) "318"
[5]=>
string(3) "317"
}
Upvotes: 0
Reputation: 342
You could use array_keys($array) instead of looping twice.
$keys = array();
foreach ($user_rated_posts as $arrs) {
$keys = array_merge($keys, array_keys($array));
}
return $keys;
Upvotes: 0
Reputation: 13766
You're overwriting the $keys
variable each time you go through your loop, so it's always only set to the last one.
$keys = array();
foreach ($user_rated_posts as $arrs) {
foreach($arrs as $key=> $value){
$keys[] = $key;
}
}
return $keys;
... that will return an actual array structure, if you actually want a comma separated list then return implode(', ', $keys);
instead.
Upvotes: 1