[英]Object of class stdClass could not be converted to string error when accessing array
I can't figure out how to get a certain value from an array that is returned to my by the Laravel PHP framework. 我无法弄清楚如何从Laravel PHP框架返回给我的数组中获取某个值。 I want to loop through this variable (called $user_ids
) and get the value of each element, like so: 我想遍历这个变量(称为$user_ids
)并获取每个元素的值,如下所示:
$sql = '(';
$limit = count($user_ids);
for ($i = 0; $i < $limit; $i++) {
if ($i == $limit ) {
$sql .= '"' . $user_ids[$i] . '")';
} else {
$sql .= '"' . $user_ids[$i] . '", ';
}
}
I keep getting the error: Object of class stdClass could not be converted to string
. 我一直收到错误: Object of class stdClass could not be converted to string
。
Here is the output of print_r($user_ids)
: 这是print_r($user_ids)
的输出:
Array ( [0] => stdClass Object ( [id] => 5 ) [1] => stdClass Object ( [id] => 6 ) [2] => stdClass Object ( [id] => 4 ) [3] => stdClass Object ( [id] => 7 ) [4] => stdClass Object ( [id] => 3 ) )
And the output of var_dump($user_ids)
: 并且var_dump($user_ids)
的输出:
array(5) { [0]=> object(stdClass)#201 (1) { ["id"]=> string(1) "5" } [1]=> object(stdClass)#205 (1) { ["id"]=> string(1) "6" } [2]=> object(stdClass)#204 (1) { ["id"]=> string(1) "4" } [3]=> object(stdClass)#206 (1) { ["id"]=> string(1) "7" } [4]=> object(stdClass)#207 (1) { ["id"]=> string(1) "3" } }
I'm sure this is something very simple but I'm just new to PHP. 我确信这很简单,但我只是PHP的新手。
Thanks, 谢谢,
Simply glue array element with commas and wrap with braces: 只需用逗号粘贴数组元素并用大括号包装:
// converting object with id param to array of ids
$user_ids = array_map(function($user) {
return (int)$user->id;
}, $user_ids);
// joining user_ids with comma
$query = (sizeof($user_ids) > 0)? '('.implode(', ', $user_ids).')' : '';
Both asef and jetawe's answers helped so I've up voted them but I found two solutions. asef和jetawe的答案都有所帮助,所以我投票给他们,但我找到了两个解决方案。 I prefer the first as it doesn't require the creation of a temporary variable ($tmp): 我更喜欢第一个,因为它不需要创建临时变量($ tmp):
$sql = '(';
$counter = 0;
$limit = count($user_ids)-1;
foreach ($user_ids as $item) {
if ($counter == $limit ) {
$sql .= '"' . $item->id . '")';
} else {
$sql .= '"' . $item->id . '", ';
}
$counter++;
}
but this also works: 但这也有效:
$sql = '(';
$limit = count($user_ids)-1;
for ($i = 0; $i <= $limit; $i++) {
$tmp = (array)$user_ids[$i];
if ($i == $limit ) {
$sql .= '"' . $tmp['id'] . '")';
} else {
$sql .= '"' . $tmp['id'] . '", ';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.