Please try this. this will return array of objects.
$result = json_decode(json_encode($data, true));
*Updated
if you want to convert all nested properties to the array, try this.
$result = json_decode(json_encode($data, true), true);
Answer from Alex on Stack OverflowPlease try this. this will return array of objects.
$result = json_decode(json_encode($data, true));
*Updated
if you want to convert all nested properties to the array, try this.
$result = json_decode(json_encode($data, true), true);
get() will return a collection. If you want to get an array of objects, use the toArray() method:
$data->toArray();
If you want to convert every object to an array too, do this:
$data->map(function($i) {
return (array)$i;
})->toArray();
To convert an object to array (as is your question) use $array = (array) $object;
you have hell lot of mistake in your blade file
@if($contactusd)
<br><br>
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Message</th>
</tr>
</thead>
@foreach($contactusd as $item)
<tr>
<td>{{ $item->name }}</td>
<td>
<ul>
<li> Email: {{ $item->email}}, Massage: {{$item->message }}</li>
</ul>
</td>
<td>{{ $item->created_at}}</td>
</tr>
@endforeach
</table>
@else
<p style="font-size: 18px">No information...</p>
@endif
or
$contactusd = ContactUS::get_content(self::$data)->toArray();
return view('cms.contactus', $contactusd);
php - Laravel. Cannot use object of type StdClass as array after toArray() convert - Stack Overflow
PHP Error: Cannot use object of type stdClass as array in Laravel - Stack Overflow
php - Cannot use object of type stdClass as array in Laravel - Stack Overflow
php - Convert laravel object to array - Stack Overflow
When you're using toArray(), you get an array of objects, so you still need to use:
$item->name
If you want to convert it to an array of arrays, do this:
$users = DB::table('users')->where('name', 'Alex')->get();
$users->transform(function($i) {
return (array)$i;
});
$array = $users->toArray();
if you want to get result as array then use get()
$query = DB::table('users')->where('name','=','Alex')->get();
if you want to get result as object use first()
$query = DB::table('users')->where('name','=','Alex')->first();
$filterQuery->get() returns you a Collection of StdClass items, and toArray() converts only Collection object, but not items inside of it (not working recursively as you want).
The easiest way is to change DB::table('view_vi_properties'); to corresponding Eloquent model, lets assume you model is ViewViProperties.In this case $filterQuery->get() will return a Collection of ViewViProperties class and toArray() will be able to convert all data to array recursivley.
If you don't want to use Eloquent then you need to convert each item separately or refer to them with object syntax like $results[0]->id.
The issue mentioned above is correct because toArray() converted the parent objects to an array, but not child objects. To convert child objects to array also can be achieved through:
$result = json_decode(json_encode($results), true);
That DB query returns a Collection of stdClass objects. It does not return a Collection of arrays. Calling toArray on that Collection will give you an array of stdClass objects.
@foreach ($statsMoneyInPlay as $value)
[ {{ $value->timestamp }}, {{ $value->moneyInPlay }} ],
@endforeach
The error is born from a misuse of the array itself. Try the following:
foreach($statsMoneyInPlay as $stat) {
echo "[" . $stat['timestamp'] . ", " . $stat['moneyInPlay'] . "]";
}
EDIT:
The $statsMoneyInPlay is an array of objects, so the proper way to access it would be:
foreach($statsMoneyInPlay as $stat) {
echo "[" . $stat->timestamp . ", " . $stat->moneyInPlay . "]";
}
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
UPDATE since version 5.4 of Laravel it is no longer possible.
You can change your db config, like @Varun suggested, or if you want to do it just in this very case, then:
DB::setFetchMode(PDO::FETCH_ASSOC);
// then
DB::table(..)->get(); // array of arrays instead of objects
// of course to revert the fetch mode you need to set it again
DB::setFetchMode(PDO::FETCH_CLASS);
For New Laravel above 5.4 (Ver > 5.4) see https://laravel.com/docs/5.4/upgrade fetch mode section
Event::listen(StatementPrepared::class, function ($event) {
$event->statement->setFetchMode(...);
});
As per your suggestions and comments I modified your code, once check and let me know.
class PrivilegesController extends Controller
{
public function getAllPrivileges()
{
$privileges = DB::table('prev_definition')->orderBy('id', 'asc')->get();
// add below line, keep your old code as it is and check
$privileges = json_decode(json_encode($privileges), true);
$privileges = $this->build_heirarchy($privileges);
$resultArray = ['status' => true, 'message' => 'Privileges found!', 'data' => $privileges];
return json_encode($resultArray);
}
public function build_heirarchy($result_set, $parent_id = 0)
{
$rs = array();
foreach ($result_set as $row) {
$row['is_checked'] = 1; // here is error
if ($row['parent_id'] == $parent_id) {
$children = $this->build_heirarchy($result_set, $row['id']);
if ($children) {
if ($children[0]['type'] == 'menu') {
$type = 'submenu';
} else {
$type = 'permission';
}
$row[$type] = $children;
}
$rs[] = $row;
}
}
return $rs;
}
}
EDIT
- There is only record with parent id 0, so it will create only one parent record, and recursively it will have appended child data. Check this.
- Now for parent id 1 it has 2 records in screenshot, so two elements will appended inside parent single most element.
- Now for parent id 2 it has 4 records in screenshot, so 4 elements will be appended inside element with id 2.
- This will go on inside to inside of every element considering parent id.
- Subsequently all data will be appended to every parent of it. So index is only one and data is appended recursively to its every relevant parent.
I hope I am clear.
if ($children)
{
if($children[0]->type=='menu')
$type = 'submenu';
else
$type = 'permission';
$row[$type] = $children;
}
toArray is changing the collection of objects into an array of objects, like it should. If you want the objects inside the collection to also be arrays, you need to first convert each object:
$collection = DB::table('users')->where([...])->take(1)->get();
$array = $collection->map(function($obj){
return (array) $obj;
})->toArray();
To use this function in your whole app, you could add a collection macro in the boot method of one of your service providers:
Collection::macro('toArrays', function () {
return $this->map(function ($value) {
return (array) $value;
})->toArray();
});
And this at the top of the file of the service providers:
use Illuminate\Support\Collection;
Then anywhere you get a set of DB results you can just call toArrays on it:
DB::table('users')->where([...])->get()->toArrays();
Since you're getting just one object, use the first() method:
$object = DB::table('users')->where([...])->first();
$array = (array)$object;
Using array_map and casting to an array should be sufficient:
$data = array_map(function($object){
return (array) $object;
}, $data);
I also wouldn't run queries inside a loop. You should try getting that data in one query from the db. Something like this could work:
$data = DB::table('order_details')
->join('orders', 'order_details.oid', '=', 'orders.oid')
->select('order_details.oid', 'orders.ostatus')
->whereIn('order_details.oid', $oid)->get();
Edit
As it has been mentioned in another answer shortly let me explain how you can accomplish the same by setting PDO to FETCH_ASSOC:
DB::setFetchMode(PDO::FETCH_ASSOC);
$data = DB::table('order_details') .... ->get();
However this changes the fetch mode globally for the rest of the request (at least if you don't open a new connection). To be save you should change it back afterwards:
DB::setFetchMode(PDO::FETCH_ASSOC);
$data = DB::table('order_details') .... ->get();
DB::setFetchMode(PDO::FETCH_CLASS);
Or even back it up first if you can't be sure what default is used:
$fetchModeBefore = DB::getFetchMode();
DB::setFetchMode(PDO::FETCH_ASSOC);
$data = DB::table('order_details') .... ->get();
DB::setFetchMode($fetchModeBefore);
On the PDO/DB object you can set the return style to assoc.
The easiest way is to JSON-encode your object and then decode it back to an array:
$array = json_decode(json_encode($object), true);
Or if you prefer, you can traverse the object manually, too:
foreach ($object as $value)
$array[] = $value->post_id;
Very simple, first turn your object into a json object, this will return a string of your object into a JSON representative.
Take that result and decode with an extra parameter of true, where it will convert to associative array
$array = json_decode(json_encode($oObject),true);
You can try to drop down to the Query\Builder instance on the Eloquent\Builder and get the records before models are hydrated.
\App\User::where('status', 'active')->getQuery()->get();
This returns the result that has been built up so far using Query\Builder@get directly, which returns a collection of stdClass objects, instead of Eloquent\Builder@get which will end up calling Query\Builder@get anyway to hydrate model instances.
You would have to check to make sure what is being called in Eloquent\Builder@get isn't needed for the particular query you are doing.
example: Global scopes App\User::...->applyScopes()->getQuery()->get()
You can use
DB::table("user")->where("status", "active")->get()->toArray();
Using DB::table("user") instead of User:: will return a Collection of stdClass objects instead of a Collection of User models. (or single, depends on closure, ->get() vs ->first())
Just keep in mind you'll lose access to any relationships or functions as defined on the User model.
I should add that
return json_decode(json_encode(\App\User::where('status', 'active')->get()->toArray()));
Could probably be converted to
$records = \App\User::where('status', 'active')->get()
return response()->json($records);