Laravel output:
Array
(
[0] = stdClass Object
(
[ID] = 5
)
[1] = stdClass Object
(
[ID] = 4
)
)
You can also get all the result always as array by changing
// application/config/database.php
'fetch' => PDO::FETCH_CLASS,
// to
'fetch' => PDO::FETCH_ASSOC,
Hope this will help.
this worked for me:
$data=DB::table('table_name')->select(.......)->get();
$data=array_map(function($item){
return (array) $item;
},$data);
or
$data=array_map(function($item){
return (array) $item;
},DB::table('table_name')->select(.......)->get());
It's also possible to typecast an object to an array. That worked for me here.
(array) $object;
will convert
stdClass Object
(
[id] => 4
)
to
Array(
[id] => 4
)
Had the same problem when trying to pass data from query builder to a view. Since data comes as object. So you can do:
$view = view('template', (array) $object);
And in your view you use variables like
{{ $id }}
If you want to get only ID in array, can use array_map:
$data = array_map(function($object){
return $object->ID;
}, $data);
With that, return an array with ID in every pos.
foreach($yourArrayName as $object)
{
$arrays[] = $object->toArray();
}
// Dump array with object-arrays
dd($arrays);
Or when toArray()
fails because it's a stdClass
foreach($yourArrayName as $object)
{
$arrays[] = (array) $object;
}
// Dump array with object-arrays
dd($arrays);
Not working? Maybe you can find your answer here:
Convert PHP object to associative array
You need to iterate over the array
for ($i = 0, $c = count($array); $i < $c; ++$i) {
$array[$i] = (array) $array[$i];
}
ans use (array)
conversion because you have array of objects of Std class and not object itself
Example:
$users = DB::table('users')->get();
var_dump($users);
echo "<br /><br />";
for ($i = 0, $c = count($users); $i < $c; ++$i) {
$users[$i] = (array) $users[$i];
}
var_dump($users);
exit;
Output for this is:
array(1) { [0]=> object(stdClass)#258 (8) { ["id"]=> int(1) ["user_name"]=> string(5) "admin" ["email"]=> string(11) "admin@admin" ["passwd"]=> string(60) "$2y$10$T/0fW18gPGgz0CILTy2hguxNpcNjYZHsTyf5dvpor9lYMw/mtKYfi" ["balance"]=> string(4) "0.00" ["remember_token"]=> string(60) "moouXQOJFhtxkdl9ClEXYh9ioBSsRp28WZZbLPkJskcCr0325TyrxDK4al5H" ["created_at"]=> string(19) "2014-10-01 12:00:00" ["updated_at"]=> string(19) "2014-09-27 12:20:54" } }
array(1) { [0]=> array(8) { ["id"]=> int(1) ["user_name"]=> string(5) "admin" ["email"]=> string(11) "admin@admin" ["passwd"]=> string(60) "$2y$10$T/0fW18gPGgz0CILTy2hguxNpcNjYZHsTyf5dvpor9lYMw/mtKYfi" ["balance"]=> string(4) "0.00" ["remember_token"]=> string(60) "moouXQOJFhtxkdl9ClEXYh9ioBSsRp28WZZbLPkJskcCr0325TyrxDK4al5H" ["created_at"]=> string(19) "2014-10-01 12:00:00" ["updated_at"]=> string(19) "2014-09-27 12:20:54" } }
as expected. Object of stdClass
has been converted to array.