I got an array in witch are nested arrays and I want to get names from those nested arrays and display them together. I have been searching a lot and can't figure out how. I am using laravel 8.
array:2 [▼
"5dd48809b061f7a3828cb5267794ce39" => array:10 [▼
"name" => "test"
]
"7d504e7f837b2f9bb03dca5f9c8da9f5" => array:10 [▼
"name" => "test2"
]
]
You can do that in basic PHP with the array_column function.
$names = array_column($array, 'name');
The above example would output:
array(
[0] => 'test',
[1] => 'test2',
);
You can also keep the ID as key, if it exists within the nested array:
$names = array_column($array, 'name', 'id');
The above example would e.g. output:
array(
[1515] => 'test',
[2522] => 'test2',
);
There are more examples in the documentation:
https://www.php.net/manual/en/function.array-column.php
Related
I'm using an API to get a list of countries in Laravel. I have been able to isolate the countries list only but the countries now have an inner array with details of the country. I only need the name. I've tried using foreach but it didn't work.
This below is the result from the api
#items: array:2 [▼
"countries" => array:198 [▼
0 => array:4 [▼
"code" => "BT"
"name" => "Bhutan"
"geonameid" => 1252634
"depends_on" => null
]
1 => array:4 [▶]
This below is the code fetching it
$response = Http::withHeaders([
'x-rapidapi-host' => 'world-geo-data.p.rapidapi.com',
'x-rapidapi-key' => '1fa601995fmshcc1d2fcc97ee24cp1ac29djsn9b9b11cc10ec',
//'x-rapidapi-key' => config('app.rapid_api_key'),
])->get('https://world-geo-data.p.rapidapi.com/countries');
//dd($response->collect());
return $response->collect()->pluck('name')
->all();
I'm trying to get only the name value. the return is returning null
I think this is what you want:
return collect($response->collect()["countries"])->pluck('name');
The result will be like:
I try to do a graph request in my laravel project to connect Microsoft API. All works fine, but I don't find a way to get single data from my request.
$info = $graph->createRequest("GET", "/groups/{id}/calendar/events?\$filter=start/dateTime ge '" . $todayDate . "T00:00' and end/dateTime lt '" . $todayDate . "T23:00'")
->addHeaders(array("Content-Type" => "application/json"))
->setReturnType(\Microsoft\Graph\Model\User::class)
->setTimeout("1000")
->execute();
Output is a large json with all information. If I just want to get $info[0]['attendees'];
I get error: Cannot use object of type Microsoft\Graph\Model\User as array in file
Why? And how to access? If I try load object like $info->attendees I got error: Trying to get property 'attendees' of non-object.
This is my output (not all) of dd($info) it includes attendees as array like "id"
array:10 [▼
0 => Microsoft\Graph\Model\Event {#1532 ▼
#_propDict: array:43 [▼
"#odata.etag" => "{tag}""
"id" => "{id}"
"createdDateTime" => "2021-03-19T10:36:08.0812445Z"
"lastModifiedDateTime" => "2021-03-19T10:36:11.9402917Z"
"attendees" => array:1 [▼
0 => array:3 [▼
"type" => "required"
"status" => array:2 [▶]
"emailAddress" => array:2 [▼
"name" => "name"
"address" => "mail"
]
]
]
It seems your array is returning an array of attendees, you have an extra level in your array. So to fetch the first attendees status, you need to use the following code:
Try this
foreach($info as $item){
foreach($item as $inf ){
$a = $inf->status
dd($a)
}
}
How to access this array object in Laravel 6, using Eloquent?
[line_items] => Array
(
[0] => stdClass Object
(
[id] => 4088662196333
[variant_id] => 29653605285997
$external = DB::table('orders')->pluck('import_order_data');
...
foreach ($external as $key => $val) {
...
Cart::updateOrCreate([
'line_item_id' => ['line_item_id' => $val['id']],
],
ErrorException
Illegal string offset 'id'
If I change it to:
'line_item_id' => ['line_item_id' => $val->id],
I get error:
ErrorException
Trying to get property 'id' of non-object
If I change it to:
'line_item_id' => ['line_item_id' => $val['line_items']->id],
I get error:
Illegal string offset 'line_items'
EDIT:
The problem was:
protected $casts = [
'import_order_data' => 'array',
];
Now I can access it like this:
dd($val['line_items'][0]['id']);
Which provides:
4092309209197
or
dd($val['line_items']);
which provides:
array:1 [▼
0 => array:26 [▼
"id" => 4092309209197
"sku" => "1605"
"name" => "Printer Ink"
Any better options on accessing the data?
EDIT:
Answer:
foreach ($val['line_items'] as $index => $lineItem) {
dd($lineItem['id']);
Which provides:
4092309209197
Is this a reasonable way to do it?
If I understand correctly, your array looks like this:
$arr = [
[
"id" => 4092309209197,
"sku" => "1605",
"name" => "Printer Ink",
....etc.....
]
];
Fine. First, since the outer array only has one item, you can do this:
$innerArr = $arr[0];
Now you've got this:
$innerArr = [
"id" => 4092309209197,
"sku" => "1605",
"name" => "Printer Ink",
....etc.....
]
And you can access it like this:
echo $innerArr["id"];
echo $innerArr["sku"];
....etc....
Or like this:
foreach($innerArr as $key => $val){
echo $key.": ".$val."\r\n";
}
I have an array from query like below:
array:84 [
0 => array:2 [
"comp" => "50007148"
"cus" => "F0401"
]
1 => array:2 [
"comp" => "50007148"
"cus" => "J0050"
]
2 => array:2 [
"comp" => "50007148"
"cus" => "L"
]
3 => array:2 [
"comp" => "50007148"
"cus" => "LT"
]
4 => array:2 [
"comp" => "50007148"
"cus" => "RP"
]
Now I need to write a query where comp, cus in above query.
$rslt = Stdetl::whereIn('comp, cus', $categories)
->where(YEAR(docdate), '=', 2019)
->get(SUM(number))->toArray();
But this query is not working. I am getting error as follows:
(1/1) FatalErrorException
Call to undefined function App\Http\Controllers\YEAR()
But this is not the only mistake in that query .
YEAR() is a mysql function, you should use whereRaw() to query this. Like this:
->whereRaw('YEAR(docdate) = 2019')
Update:
For your whereIn() part, you have to make two queries, one for each column. So you will have to get the correct values from the array. This can be done using array_map.
For example:
->whereIn('comp', array_map(function($cat) { return $cat['comp']; }, $categories))
->whereIn('cus', array_map(function($cat) { return $cat['cus']; }, $categories))
You can't use whereIn like that, use this way
$rslt=Stdetl::whereIn('comp', $categories)
->whereIn('cus', $categories)
->where(date('Y', strtotime(docdate)), '=', 2019)
->get(SUM(number))->toArray();;
I have an array that contains ids of selected options in select list (html).
In Laravel it looks as:
<?=Form::select('type_work[]', $work_types, old('type_work'), ['multiple' => "multiple", 'size' => 15, 'id' => 'type_work', "class" => "selectpicker form-control"]);?>
Where second parameter is incoming data to build options, and third parameter is array of selected options (id).
Why it does not work in Laravel?
This is incoming data:
Collection {#488 ▼
#items: array:14 [▼
14 => "Роботи, пов’язані з проведенням технічної експертизи."
]
}
This is selected data:
Collection {#408 ▼
#items: array:1 [▼
14 => "Роботи, пов’язані з проведенням технічної експертизи."
]
}
The amount type_work[] you have used is considered as the ID of the field. You must specify the value of the Name as an array.
Change the code as below
{{Form::select('type_work',$work_types,null,array('multiple'=>'multiple','name'=>'type_work[]'))}}
So you code should be like
<?=Form::select('type_work[]', $work_types, null, ['multiple' => true, 'size' => 15, 'id' => 'type_work', "class" => "selectpicker form-control"]);?>
Reference
Docs