im using laravel 7 and trying to get datas from api use http.
when i use dd('$datas'),i got this
array:1 [▼"manajemen_sdm" => array:4 [▼ 0 => array:9 [▼ "id_karyawan" => "2" "nama" => "Koko Hendriko" "gender" => "Laki-Laki" "ttl" => "1998-04-07" "alamat" => "Kp.Palasari " "no_telp" => "821863141" "email" => "kokohendriko#gmail.com" "npwp" => "89678923652" "golongan" => "B" ] 1 => array:9 [▶] 2 => array:9 [▶] 3 => array:9 [▶] ] ]
my controller
public function index()
{
$datas = Http::get('https://projectsoadenis.000webhostapp.com/api')->json();
return view('sdm.index',compact('datas'));
}
view
#foreach ($datas as $datasdm)
<tr>
<td>{{$no++}}</td>
<td>{{$datasdm['id_karyawan']}}</td>
<td>{{$datasdm['nama']}}</td>
<td>{{$datasdm['gender']}}</td>
<td>{{$datasdm['ttl']}}</td>
<td>{{$datasdm['alamat']}}</td>
<td>{{$datasdm['no_telp']}}</td>
<td>{{$datasdm['email']}}</td>
<td>{{$datasdm['npwp']}}</td>
<td>{{$datasdm['golongan']}}</td>
</tr>
#endforeach
If you look at the data you are getting back from the API, your data is actually nested inside objects that live under a manajemen_sdm property.
Your loop should work correctly if you update it to loop over the manajemen_sdm key:
#foreach ($datas['manajemen_sdm'] as $datasdm)
<tr>
<td>{{$no++}}</td>
<td>{{$datasdm['id_karyawan']}}</td>
<td>{{$datasdm['nama']}}</td>
<td>{{$datasdm['gender']}}</td>
<td>{{$datasdm['ttl']}}</td>
<td>{{$datasdm['alamat']}}</td>
<td>{{$datasdm['no_telp']}}</td>
<td>{{$datasdm['email']}}</td>
<td>{{$datasdm['npwp']}}</td>
<td>{{$datasdm['golongan']}}</td>
</tr>
#endforeach
Related
I want to have an array with the info about each registration type associated with a registration. For example if for the registration with id "1" the user selected two registration types of type "General" and one of the type "Plus" the $regTypes array should have this content with 2 item:
'registrationTypes' => [
[
'name' => 'general',
'price' => '5',
'quantity' => '2'
],
[
'name' => 'plus',
'price' => '10',
'quantity' => '1'
]
]
The registration_types table have the name and the price. So I have this query to get some info about a registration in a conference.
$registration = Registration
::with('conference', 'Conference.registrationTypes')->where('id', 1)->first();
And then I have this code to create the array with the necessary info:
$regTypes = [];
foreach($registration->conference->registrationTypes as $key=>$registrationType){
$regTypes [
'regType' => [
'name' => $registration->conference->registrationTypes[$key]['name'],
'price' => $registration->conference->registrationTypes[$key]['price']
]
];
}
My doubt is how to also store the quantity in the $regTypes array. Because the quantity is not stored in the database.
Maybe to get the quantity is necessary to do antoher query. With this code below:
$registrationTypeDetails = Registration::with('participants:id,registration_type_id,registration_id')->find($regID);
//dd($registrationTypeDetails);
$type_counts = [];
foreach ($registrationTypeDetails->participants as $p) {
$name = $p->registration_type->name;
if (!isset($type_counts[$name])) {
$type_counts[$name] = 0;
}
$type_counts[$name]++;
}
dump($type_counts);
The $type_counts shows the quantity of each registration type associated with the registration:
array:2 [▼
"general" => 2
"plus" => 1
]
Do you know how to use this $type_counts content to store the quantity properly in the $regTypes array?
To directly answer your question (IE not change the controller code, just "use this $type_counts content to store the quantity properly in the $regTypes array"), I'm hopeful this should work for you:
$regTypes = [];
foreach($registration->conference->registrationTypes as $key=>$registrationType){
$typeName = $registration->conference->registrationTypes[$key]['name'];
$regTypes [
'regType' => [
'name' => $typeName,
'price' => $registration->conference->registrationTypes[$key]['price'],
'quantity' => $type_counts[$typeName]
]
];
}
Basically just pulling the count from the $type_counts array based on the name of the Registration Type being the key that you added in the foreach ($registrationTypeDetails->participants as $p) loop.
Depending upon what you are after, it might be easier just to loop on the registration types, rather than go through $registration->conference->registrationTypes. This way you don't have duplicates. But that assumes you don't want duplicates :)
I hope this code useful for you .If you need the number of participants in any type, you can use the following code:
$registration = Registration::with('conference','Conference.registrationTypes','Conference.registrationTypes.participants')
->where('id',$regID)->first();
$result=$registration->conference->registrationTypes->each(function ($item, $key) use($registration) {
$item['try_count']=$item->participants->count();
});
dd($result->toArray());
I added the try_count variable to the final result:
array:2 [▼
0 => array:6 [▼
"id" => 1
"name" => "general"
"price" => 0
"conference_id" => 1
"try_count" => 8
"participants" => array:8 [▼
0 => array:5 [▶]
1 => array:5 [▶]
2 => array:5 [▶]
3 => array:5 [▶]
4 => array:5 [▶]
5 => array:5 [▶]
6 => array:5 [▶]
7 => array:5 [▶]
]
]
1 => array:6 [▼
"id" => 2
"name" => "plus"
"price" => 1
"conference_id" => 1
"try_count" => 5
"participants" => array:5 [▼
0 => array:5 [▶]
1 => array:5 [▶]
2 => array:5 [▶]
3 => array:5 [▶]
4 => array:5 [▶]
]
]
]
I have completely changed the format of my array now, and I had what I hope is a simple misunderstanding on my part. So my array now looks like the following
array:9 [▼
0 => array:4 [▼
"leadData" => array:7 [▼
"LeadID" => "1232806"
"Client" => "Some Client"
"LeadName" => "Test"
"Owner" => "Someone"
"Value" => "2160.00"
]
"clientData" => array:2 [▼
"Prospect" => "No"
]
"quoteData" => array:8 [▼
"QuoteID" => "Q0020"
"ProjectName" => "Test"
"Amount" => "1234"
]
"customData" => array:2 [▼
0 => array:1 [▼
"Type" => "New"
]
1 => array:1 [▼
"Month" => "June 16"
]
]
]
2 => array:4 [
...
]
]
So it is essentially now 4 inner arrays. Now if I do the following, I can print out all the data for the leadData inner array
foreach($leadArray as $array)
<tr>
foreach($array['leadData'] as $leadKey => $leadData)
<td>
{{ $leadData }}
</td>
endforeach
</tr>
endforeach
That works fine. However, I only want to display certain parts of this array. I would have presumed doing something like the following would work
foreach($leadArray as $array)
<tr>
foreach($array['leadData'] as $leadKey => $leadData)
<td>
{{ $leadData['LeadID'] }}
</td>
<td>
{{ $leadData['LeadName'] }}
</td>
endforeach
</tr>
endforeach
However if I do this I get and Illegal String Offset error. Is this not how I would access this data?
p.s. Ignore the way I do the foreach loop etc, this is because I am using a template engine.
Thanks
You don't have to loop over the second array, you can use the keys to get the data.
foreach($leadArray as $array)
<tr>
<td>
{{ $array['leadData']['LeadID'] }}
</td>
<td>
{{ $array['leadData']['LeadName'] }}
</td>
</tr>
endforeach
Your main array will be like this, where you want to work, right?
<pre>
$aMainArray = array(
0 => array(
"leadData" => array(
"LeadID" => "1232806",
"Client" => "Some Client",
"LeadName" => "Test",
"Owner" => "Someone",
"Value" => "2160.00",
)
)
);
foreach ($aMainArray AS $aSubArray) {
print_r($aSubArray);
// You can echo your required values like below
echo $aSubArray['leadData']['LeadID'];
echo $aSubArray['leadData']['LeadName'];
// OR like this one
foreach ($aSubArray AS $value) {
echo $value['LeadID'];
echo $value['LeadName'];
}
}
</pre>
So I have a piece of code that I have been fighting with for a while now.
Here is the code that I have
<?php
namespace App\Http\Controllers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Requests\SearchRequest;
use Vinelab\Http\Client as HttpClient;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class SearchResults extends Controller
{
public function index()
{
return view('results.search-results');
}
public function store(Requests\SearchRequest $request)
{
$searchPhrase = $request->input('search');
$client = new HttpClient;
$response = $client->get('https://www.reddit.com/search.json?q='. urldecode($searchPhrase) .'');
$response = collect($response->json());
$responseDecode = json_decode($response, true);
$SearchResultsArray = $responseDecode;
dd($SearchResultsArray);
}
}
And this returns a nested array that looks like this
array:2 [▼
"kind" => "Listing"
"data" => array:5 [▼
"facets" => []
"modhash" => ""
"children" => array:25 [▼
0 => array:2 [▼
"kind" => "t3"
"data" => array:52 [▶]
]
1 => array:2 [▶]
2 => array:2 [▶]
3 => array:2 [▶]
4 => array:2 [▶]
5 => array:2 [▶]
6 => array:2 [▶]
]
"after" => "t3_38lgh9"
"before" => null
]
]
I am trying to access the title attribute that is inside each of these
1 => array:2 [▶]
2 => array:2 [▶]
3 => array:2 [▶]
4 => array:2 [▶]
5 => array:2 [▶]
6 => array:2 [▶]
7 => array:2 [▶]
I want to parse them to an array that I can send to a Laravel View.
Every time I try to acccess this I get undefined index or offset and I am at a loss as to how to go about this.
Can anybody assist me in finding a solution to this problem?
Edit ---------------------
I am now using this and it is working perfectly
$allData=[];
$counter = 1;
foreach ($posts as $post) {
//foreach post get the data and store it in a database
$allData[$counter]['title']= $post['data']['title'];
$sentiment = SentimentAnalysis::decision($allData[$counter]['title']);
$allData[$counter]['created']= $post['data']['created'];
RedditPosts::create([
'title' => $allData[$counter]['title'],
'created' => date($allData[$counter]['created']),
'sentiment' => $sentiment,
'search_identifier' => $search_id,
'search_phrase' => $searchPhrase
]);
$counter ++;
}
Basically you would need three foreach in your case to achieve the nested arrays like this
foreach($SearchResultsArray as $ThreeLevelArray){
foreach($ThreeLevelArray as $TwoLevelArray) {
foreach($TwoLevelArray as $OneevelArray) {
//your here son :)
}
}
}
$allData=[];
$counter = 1;
foreach ($posts as $post) {
//foreach post get the data and store it in a database
$allData[$counter]['title']= $post['data']['title'];
$sentiment = SentimentAnalysis::decision($allData[$counter]['title']);
$allData[$counter]['created']= $post['data']['created'];
RedditPosts::create([
'title' => $allData[$counter]['title'],
'created' => date($allData[$counter]['created']),
'sentiment' => $sentiment,
'search_identifier' => $search_id,
'search_phrase' => $searchPhrase
]);
$counter ++;
}
I am trying to pass an array of objects to the view and then use the blade templating engine to loop through them.
The data is being returned from a Parse.com query and is structured like this:
[
{
"Params": [],
"difficulty": "Medium",
"exerciseDescription": "Sit on a gym ball with a dumbbell in each hand. Bend your elbows to lift the dumbbells to your shoulder.",
"exerciseID": "1024",
"exerciseName": "Bicep Curl Sitting on Gym Ball",
"images": [
2758,
2759,
2760
],
"objectId": "9xjQ4WVo6e",
"tags": [
"Dumbbell",
"Gym Ball",
"Flexion"
],
"words": [
"seated",
"dumbbell",
"arm",
"curl"
]
}
]
I am getting this using this query:
public function about()
{
$programmeId = 'T8iqZhtDqe';
$query = new ParseQuery("PrescribedProgrammes");
try {
$programme = $query->get($programmeId);
// The object was retrieved successfully.
} catch (ParseException $ex) {
echo $ex;
// The object was not retrieved successfully.
// error is a ParseException with an error code and message.
}
$exerciseData = $programme->get("exerciseData");
$programmeTitle = $programme->get("prescribedProgrammeTitle");
// return view('pages.about', compact('exerciseData','programmeTitle'));
return view('pages.about')->with('exerciseData', $exerciseData);
}
And to test this I have been trying:
#foreach($exerciseData as $exercise => $value)
{{ $exercise->exerciseName }}
#endforeach
However I am getting a Array to string conversion error. Coming from a angularJS background I am hoping to pass my array of objects to the view and then loop through them as I see fit.
Would this be considered poor form?
EDIT
Running dd($exerciseData)
array:7 [▼
0 => array:9 [▼
"Params" => []
"difficulty" => "Medium"
"exerciseDescription" => "Sit on a gym ball with a dumbbell in each hand. Bend your elbows to lift the dumbbells to your shoulder."
"exerciseID" => "1024"
"exerciseName" => "Bicep Curl Sitting on Gym Ball"
"images" => array:6 [▶]
"objectId" => "9xjQ4WVo6e"
"tags" => array:6 [▶]
"words" => array:8 [▶]
]
1 => array:9 [▶]
2 => array:9 [▶]
3 => array:9 [▶]
4 => array:9 [▶]
5 => array:9 [▶]
6 => array:9 [▶]
]
I think you're using the key of the array instead of the value. For example the default PHP foreach looks like the following:
foreach($array as $key => $value) {
// code
}
Edit:
After looking at the dump of $exerciseData it appears that PHP is serializing the JSON into an array, so this changes the answer.
If you return this to the view:
return view('quiz.create', compact('programmeTitle', 'exerciseData'));
Then have the following in your view it should work as I have tested it locally:
<h2>{{$programmeTitle}}</h2>
#foreach ($exerciseData as $key => $exercise)
<p>{{$exercise['exerciseName']}}</p>
#endforeach
I have a following assoc array:
45111 => array:16 [▼
"სქესი" => array:1 [▶]
"ასაკი" => array:1 [▶]
"შემოსავალი" => array:1 [▶]
"შემოსავლის ტიპი" => array:1 [▶]
"Existing PMT" => array:1 [▶]
"min(payment cnt)" => array:1 [▶]
"guarantor" => array:1 [▶]
"reqeusts last 3m / req last 12m" => array:1 [▶]
"micro loans cnt last 12m (closed)" => array:1 [▶]
"micro loans cnt last 3m (closed)" => array:1 [▶]
"loans deliquency days" => array:1 [▶]
"Past PMT" => array:1 [▶]
"RiskGrade" => array:1 [▶]
"ProbabilityOfDefault" => array:1 [▶]
"Total" => array:1 [▶]
"penalties paid" => array:1 [▼
0 => 90.0
]
]
I'd like to iterate over the second array using first index. However, it returns "Undefined offset" exception. I guess $v[0] is not supported in blade. What is the correct way to do this?
#foreach ($creditInfo as $k => $v)
#foreach ($v[0] as $y => $x)
<tr>
<td>{{$y}}</td>
</tr>
#endforeach
#endforeach
It's just executing PHP so to say it's not supported in Blade makes no sense. The error happens because $v[0] does not exist as 0 is an undefined offset. $v['Total'] would be fine though and would return an array.
Since the first key is სქესი, 0 isn't going to work but if you are only concerned about the first item, you can use current to grab the first.
#foreach ($creditInfo as $k => $v)
#foreach (current($v) as $y => $x)
<tr>
<td>{{$y}}</td>
</tr>
#endforeach
#endforeach
That will loop through the array in $v['სქესი']