Hi First i am getting dat from database as an array then I want to convert my array data into object I tried many function but not work in laravel api .I want to convert array data into object and return as JSON for API i google it several time but did not find any solutions any body help thanks in advance.
for api i am using this
return response()->json(['data' => $categories, 'status_code' => 200, 'status' => true],200);
i have tried
cateogry is an array $categories
$data_object = (object)$categories;
$data_array = (array)$categories;
dd($data_array);
dd($data_object);
both return same result
this is the result
array:14 [
37 => array:5 [
"id" => 37
"name" => "Red abya"
"alias" => "red-abya"
"is_featured" => 0
]
38 => array:5 [
"id" => 38
"name" => "Black Dress"
"alias" => "black-dress"
"is_featured" => 0
]"is_featured" => 0
]
1 => array:6 [
"id" => 1
"name" => "Abayas"
"alias" => "abayas"
"is_featured" => 1
"sub_categories" => array:2 [
0 => array:5 [
"id" => 37
"name" => "Red abya"
"alias" => "red-abya"
"is_featured" => 0
]
1 => array:5 [
"id" => 36
"name" => "White abaya"
"alias" => "white-abaya"
"is_featured" => 0
]
]
]
25 => array:5 [
"id" => 25
"name" => "Discount"
"alias" => "discount"
"is_featured" => 0
]
]
If you want JSON at the end you can try changing this:
$data_object = (object)$categories;
to
$data_object = (object)$categories;
$data_object->toJson();
dd($data_object);
I will assume $categories is a collection array. Then in your view you can json_encode($data_object) it.
Try this
$categories = array_map(function($categories){
return (object)$categories;
}, $categories);
if you use postman you send and receive data in json format. so for this you can use json_encode() to convert data to json format and json_decode() to convert data to array() format. also in laravel you get data by Request instans and send response by response() helper, so if you need get data in array format you can use this:
$data_array = (array)$request->all()
and for send data use:
response()->json($data_array , 200);
if you want stdclass use (object) instead array
Related
I have 2 arrays and I want to merge them. (I can merge them) but I also need to include their unique keys in merged results and that part I cannot achieve.
sample
$prices = [
['112802' => "500000"],
['113041' => "1000000"],
];
$notes = [
['112802' => "note 2"],
['113041' => "note 1"],
];
$collection = collect($prices);
$zipped = $collection->zip($notes);
$zipped->toArray();
Unique keys are 112802 and 113041.
When I merge my array all I get is this:
[
[
"1000000",
"note 1"
],
[
"500000",
"note 2"
]
]
What I'm looking for is like this:
[
[
"id" => "112802",
"price" => "500000",
"note" => "note 2",
],
[
"id" => "113041",
"price" => "1000000",
"note" => "note 1",
]
}]
any suggestion?
This does what you want with the data you provide.
NOTE it will only work if your 2 arrays are the same size and the the keys are in the same order.
If this data comes from a database, it is likely it could have been produced in the format you actually wanted rather than having to fiddle with the data post fetch.
$prices = [
['112802' => "500000"],
['113041' => "1000000"],
];
$notes = [
['112802' => "note 2"],
['113041' => "note 1"],
];
$new = [];
foreach ($prices as $i=>$pr){
$k = key($pr);
$new[] = [ 'id' => $k,
'price' => $pr[$k],
'note' => $notes[$i][$k] ];
}
print_r($new);
RESULT
Array
(
[0] => Array (
[id] => 112802
[price] => 500000
[note] => note 2
)
[1] => Array (
[id] => 113041
[price] => 1000000
[note] => note 1
)
)
Here's another solution using some of Laravel's Collection methods.
It's not the most elegant, but it can be a starting point for you.
$prices = collect([
['112802' => "500000"],
['113041' => "1000000"],
])->mapWithKeys(function($item) {
// This assumes that the key will always be the ID and the first element is the price.
// Everythng else for each element will be ignored.
$id = array_keys($item)[0];
return [$id => ["id" => $id, "price" => reset($item)]];
});
$notes = collect([
['112802' => "note 2"],
['113041' => "note 1"],
])->mapWithKeys(function($item) {
$id = array_keys($item)[0];
return [$id => ["id" => $id, "note" => reset($item)]];
});
$result = $prices->zip($notes)->map(function ($item) {
// Feel free to call `toArray()` here if you don't want a Collection.
return collect($item)->mapWithKeys(function ($a) { return $a; });
});
Below is the $result (called using dd()).
Illuminate\Support\Collection {#1886 ▼
#items: array:2 [▼
0 => Illuminate\Support\Collection {#1888 ▼
#items: array:3 [▼
"id" => 112802
"price" => "500000"
"note" => "note 2"
]
}
1 => Illuminate\Support\Collection {#1889 ▼
#items: array:3 [▼
"id" => 113041
"price" => "1000000"
"note" => "note 1"
]
}
]
}
It's achieved by extracting the ID so that the zip can join there, but then we need a little hack with the map and mapWithKeys in the $result.
That's just because otherwise each element in $result will still have two separate arrays for $prices and $notes.
I have he next array looks like:
array:50 [▼
0 => array:39 [▶]
1 => array:39 [▶]
2 => array:39 [▶]
]
So I want to get arrays with a value in common, for example:
array:39 [▼
"id" => 121
"user" => 368
]
array:39 [▼
"id" => 121
"user" => 3687
]
array:39 [▼
"id" => 500
"user" => 452
]
I want to get the two arrays with the attribute
id 121, I was trying to looping the array with foreach looks like:
foreach ($info as $val){
foreach($info as $f ){
if($f["id"]==$val["id"]){
//get the multiple arrays
}
}
}
So, I can't get all the arrays, some idea to how can do that?
I'd use a Collection.
collect your array of arrays:
$collection = collect([
[
"id" => 121
"user" => 368
],
[
"id" => 121
"user" => 3687
],
[
"id" => 500
"user" => 452
]
]);
Use the where method to filter based on a specific key's value:
$filtered = $collection->where('id', 121);
$filtered->all();
/*
[
['id' => '121', 'user' => 368],
['id' => '121', 'user' => 3687],
]
*/
Other where-like methods are available. Be sure to read through all of the documentation on Collections, it's full of great examples!
If you're now convinced that you should use Collections for everything, check out Adam Wathan's awesome book (and other resources): Refactoring to Collections (not free)
I am trying to iterate over this array in order to take all league values (league_id,name,type etc)
array:1 [▼
"api" => array:2 [▼
"results" => 970
"leagues" => array:970 [▼
0 => array:13 [▼
"league_id" => 1
"name" => "World Cup"
"type" => "Cup"
"country" => "World"
"country_code" => null
"season" => 2018
"season_start" => "2018-06-14"
"season_end" => "2018-07-15"
"logo" => "https://media.api-football.com/leagues/1.png"
"flag" => null
"standings" => 1
"is_current" => 1
]
1 => array:13 [▼
"league_id" => 2
"name" => "Premier League"
"type" => "League"
"country" => "England"
"country_code" => "GB"
"season" => 2018
"season_start" => "2018-08-10"
"season_end" => "2019-05-12"
"logo" => "https://media.api-football.com/leagues/2.png"
"flag" => "https://media.api-football.com/flags/gb.svg"
"standings" => 1
"is_current" => 0
]
.......
but until now,with the following code:
$request = json_decode($request->getBody()->getContents(), true);
foreach ($request as $array=>$val) {
foreach ($val['leagues'] as $id) {
dd($id);
}
}
the only thing that i can get is the first array only and not the rest:
array:13 [▼
"league_id" => 1
"name" => "World Cup"
"type" => "Cup"
"country" => "World"
"country_code" => null
"season" => 2018
"season_start" => "2018-06-14"
"season_end" => "2018-07-15"
"logo" => "https://media.api-football.com/leagues/1.png"
"flag" => null
"standings" => 1
"is_current" => 1
]
any help?
The dd() function you are calling is killing the execution of your script on your first iteration.
From the Laravel Docs:
The dd function dumps the given variables and ends execution of the script.
If you do not want to halt the execution of your script, use the dump function instead.
Just iterate over it like so:
$request = json_decode($request->getBody()->getContents(), true);
foreach ($request['leagues'] as $id=>$league) {
print_r(compact('id', 'league')); // To see the id and value array
}
Hope this helps,
I don't know what I'm doing wrong since it works with all the other models in the app. I refreshed and reseeded the database multiple times. The models extend the same abstract methods.
This is the code in the controller:
$substrates = $this->substrates->all()->toArray();
$temp = json_encode($substrates);
dd($temp, json_last_error(), json_last_error_msg(), $substrates);
This is the dd() output:
false
8
"Type is not supported"
array:119 [▼
0 => array:21 [▼
"id" => 1
"name" => "Wood Free"
"machine_id" => 2
"classification" => "Cover"
"origins" => "Coming Soon"
"duplex" => true
"color" => "Translucents"
"texture" => "Leather"
"finish" => "Felt"
"product_type" => "Sheet"
"caliper" => "0.06"
"m_weight" => 70
"width" => "46.40"
"height" => "32.00"
"pic" => stream resource #17 ▶}
"price" => "0.30"
"created_by" => 38
"updated_by" => 16
"deleted_at" => null
"created_at" => "2018-01-27 08:00:11"
"updated_at" => "2018-01-27 08:00:11"
]
1 => array:21 [▶] ....
When I use JSON_PARTIAL_OUTPUT_ON_ERROR I get a json string.
The reason for the error is the fact, that you're storing a stream resource in pic field of the serialised object that can't be serialised to JSON.
You can tell Eloquent model to skip selected attributes when they're converted to an array by setting a $hidden attribute in your model:
class Substrate extends Model {
protected $hidden = ['pic'];
}
It sounded crazy simple to me at first but I can't find the solution!
Here is My collection :
Collection {#433
#items: array:432 [
0 => array:5 [
"word_id" => 12218
"name" => "ordered"
"rank" => 12217
"is_real" => 1
"id" => 1
]
1 => array:5 [
"word_id" => 12097
"name" => "one-dimensional"
"rank" => 12096
"is_real" => 1
"id" => 2
]
2 => array:5 [
"word_id" => 19679
"name" => "watery"
"rank" => 19678
"is_real" => 1
"id" => 3
]
.
.
.
But I want it to be like this :
Collection {#433
#items: array:432 [
0 => array:5 [
"name" => "ordered"
"id" => 1
]
1 => array:5 [
"name" => "one-dimensional"
"id" => 2
]
2 => array:5 [
"name" => "watery"
"id" => 3
]
.
.
.
How can it be done with laravel collection? Do I have to change my collection to array and do the manipulation myself? How?
Or you can also use
$collection = $collection ->map(function ($item) {
return collect($item)->forget(['work_id','rank','is_real']);
});
$collection = $collection->map(function ($item) {
return array_only($item, ['id', 'name']);
});
You can use the only() method.
The only method returns the items in the collection with the specified
keys
$collection = $collection->map(function ($item) {
return $item->only(['id', 'name'])
});
This way your collection still remains as collections;
Please note, only() method is only available for Laravel collections
not for an array
An alternative approach could be to use the Arr::only() helper to reduce the items:
$collection = $collection->map(static fn($item) => Arr::only($item, ['id', 'name']));