PHP Array Looping
I have an array that looks like this:
Array
(
[0] => stdClass Object
(
[user_id] => 10
[date_modified] => 2010-07-25 01:51:48
)
[1] => stdClass Object
(
[user_id] => 16
[date_modified] => 2010-07-26 14:37:24
)
[2] => stdClass Object
(
[user_id] => 27
[date_modified] => 2010-07-26 16:49:17
)
[3] => stdClass Object
(
[user_id] => 79
[date_modified] => 2010-08-08 18:53:20
)
)
and what I need to do is print out the user id's comma seperated so:
10, 16, 27, 79
I'm guessing it'd be in a for loop but i'm looking for the most efficient way to do it in 开发者_运维百科PHP
Oh and the Array name is: $mArray
I'm trying the methods below but I keep getting this error: Fatal error: Cannot use object of type stdClass as array in
$length = sizeof($mArray);
sort($mArray);
foreach($mArray as $item)
{
echo $item['user_id'] . ($item !== $mArray[$length]) ? ', ' : '';
}
Remove the sort if you don't need it in order.
Whenever I need to make a delimited list (in this case by a comma), I start with an array and implode() it with the delimiter. In this case the delimiter would be the comma + the space:
$user_ids = array();
foreach($mArray as $item) {
$user_ids[] = $item['user_id'];
}
$comma_delimited_list = implode(', ', $user_ids);//magic
$firstTime = true;
foreach($mArray as $k => $cur)
{
//echo $firstTime ? $firstTime = false : ', '; //this one-liner cna replace the following two, kind of unclear but i like it
if (!$firstTime) echo ', ';
else $firstTime = false;
echo $cur->user_id;
}
This is more fun:
$f = function($a,$b) {$c = $a ? ', ' : ''; return $a . $c . $b->user_id;};
echo array_reduce($f, $mArray, '');
James alludes to using join
, which is a good idea and avoids the trailing comma issue
$newArr = array_map(function($x) {return $x->user_id;}, $mArray); //make array of just user-ids
echo join(', ',$newArr); // implode === join, join is an alias of implode
I'd do it like this:
$output = "";
foreach($mArray as $i => $val) {
$output .= $val->user_id . ", " ;
}
$output = trim($output, ", ");
Heck, you could probably use join
and remove the foreach loop altogether!
精彩评论