I am trying to get all data i need in one variable
--Subject
---Chapters related to subject
----Topics related to chapter
And this is what i have done!
$subjects = Subject::all();
$chapters = Chapter::all();
$topics = Topic::all();
foreach ($subjects as &$subject)
{
$i = 0;
$subject->related_chapters = array();
$chapters_reltn = array();
foreach ($chapters as $chapter)
{
if ($chapter->subject_id == $subject->id)
{
$chapters_reltn[$i]['id'] = $chapter->id;
$chapters_reltn[$i]['name'] = $chapter->name;
$j = 0;
foreach ($topics as $topic)
{
if ($topic->chapter_id == $chapter->id)
{
$chapters_reltn[$i]['related_topics'][$j]['id'] = $topic->id;
$chapters_reltn[$i]['related_topics'][$j]['name'] = $topic->name;
$j++;
}
}
$i++;
}
};
$subject->related_chapters = $chapters_reltn;
}
When i dd() in laravel, i see all the data arranged in structure i wanted.
The problem comes when accessing a specific data like so,
#foreach($subjects as $subject)
{{ $subject->name }}
{{ $subject->related_chapters[0]['name'] }}
#endforeach
i get an error:
Undefined offset: 0
Is there a better way of structuring my array, and getting data correctly. Please help!
Undefined offset is an notice that comes when you try to access an array which does not exist . Make sure that a value exists in that index or you can do something like this just before accessing the value
If (isset ( $subject->related_chapters[0]['name']))
Related
I want to display something like this: (which sort the dates from the original array into new arrays)
01.01.2021: 5
02.01.2021: 3
and so on... I already got the info stored in an array, and sorted by date. I just cannot figure out how to add a similar date-row to an array within that array automatically. not only that, but I want to echo it at the same time.
I'm absolutely stuck on this. Please help. By the way, the record->date is a format like this: 01.01.2021 15:00
#php
$records = DB::table('bookings')->get();
$records = $records->sortBy('date')->toArray();
$array = array();
#endphp
#foreach($records as $record)
somehting in here
#endforeach
After some answers, I now have this: But it still does not work. Error: "Undefined array key "2021-07-30 15:00""
<?php
$records = DB::table('bookings')->get()->sortBy('date')->toArray();
$array = array();
foreach($records as $record){
if(array_key_exists($array[$record->date], $array)) {
$array[$record->date] = $array[$record->date] +1;
}else{
$array[$record->date] = 1;
}
}
foreach($array as $value_key => $value_value){
echo $value_key . " : " . $value_value;
}
?>
After some quick debugging, I think the problem with this code is that it checks for an array which is not there, and it fails. But when I make the array in the else statement (with commenting out stuff) then it works. So I have still no idea how o implement the statement to check if it exists or not.
#php
$records = DB::table('bookings')->get();
$records = $records->sortBy('date')->toArray();
$array = array();
#endphp
#foreach($records as $record)
if (array_key_exists($array[$record->date],$array))
{
$array[$record->date] = $array[$record->date] + 1;
}
else
{
$array[$record->date] = 1;
}
#endforeach
#foreach ($array as $value_key => $value_value)
{{$value_key}} {{$value_value}}
#endforeach
try this
#php
$records = App\Booking::pluck('date')->toArray();
foreach ($records as $record){
count[] = App\Booking::where('date' , $record)->pluck('date')->count();
}
dd(array_unique($records) , count);
#endphp
if input is
01.01.2021
01.01.2021
01.01.2021
01.02.2021
01.02.2021
01.03.2021
01.04.2021
then output will be
01.01.2021 , 3
01.02.2021 , 2
01.03.2021 , 1
01.04.2021 , 1
I found the working code, thanks to some google searches and some good answers. If anyone wants it, here it is:
<?php
$records = DB::table('bookings')->get()->sortBy('date')->toArray();
$array = array();
foreach($records as $record){
if(isset($array[$record->date]) ? $array[$record->date] : null) {
$array[$record->date] = $array[$record->date] +1;
}else{
$array[$record->date] = 1;
}
}
?>
#foreach($array as $value_key => $value_value)
{{$value_key . " : " . $value_value}}
<br>
#endforeach
And the output will be something like 01.05.2021 15:00: 3
Why am I getting this PHP Warning?
Invalid argument supplied for foreach()
Here is my code:
// look for text file for this keyword
if (empty($site["textdirectory"])) {
$site["textdirectory"] = "text";
}
if (file_exists(ROOT_DIR.$site["textdirectory"].'/'.urlencode($q).'.txt')) {
$keywordtext =
file_get_contents(ROOT_DIR.$site["textdirectory"].'/'.urlencode($q).'.txt');
}
else {
$keywordtext = null;
}
$keywordsXML = getEbayKeywords($q);
foreach($keywordsXML->PopularSearchResult as $item) {
$topicsString = $item->AlternativeSearches;
$relatedString = $item->RelatedSearches;
if (!empty($topicsString)) {
$topics = split(";",$topicsString);
}
if (!empty($relatedString)) {
$related = split(";",$relatedString);
}
}
$node = array();
$node['keywords'] = $q;
2
$xml = ebay_rss($node);
$ebayItems = array();
$totalItems = count($xml->channel->item);
$totalPages = $totalItems / $pageSize;
$i = 0;
foreach ($xml->channel->item as $item) {
$ebayRss =
$item->children('http://www.ebay.com/marketplace/search/v1/services');
if ($i>=($pageSize*($page-1)) && $i<($pageSize*$page)) {
$newItem = array();
$newItem['title'] = $item->title;
$newItem['link'] = buyLink($item->link, $q);
$newItem['image'] = ebay_stripImage($item->description);
$newItem['currentbid'] = ebay_convertPrice($item->description);
$newItem['bidcount'] = $ebayRss->BidCount;
$newItem['endtime'] = ebay_convertTime($ebayRss->ListingEndTime);
$newItem['type'] = $ebayRss->ListingType;
if (!empty($ebayRss->BuyItNowPrice)) {
$newItem['bin'] = ebay_convertPrice($item->description);
}
array_push($ebayItems, $newItem);
}
$i++;
}
$pageNumbers = array();
for ($i=1; $i<=$totalPages; $i++) {
array_push($pageNumbers, $i);
}
3
// get user guides
$guidesXML = getEbayGuides($q);
$guides = array();
foreach ($guidesXML->guide as $guideXML) {
$guide = array();
$guide['url'] = makeguideLink($guideXML->url, $q);
$guide['title'] = $guideXML->title;
$guide['desc'] = $guideXML->desc;
array_push($guides,$guide);
}
What causes this warning?
You should check that what you are passing to foreach is an array by using the is_array function
If you are not sure it's going to be an array you can always check using the following PHP example code:
if (is_array($variable)) {
foreach ($variable as $item) {
//do something
}
}
This means that you are doing a foreach on something that is not an array.
Check out all your foreach statements, and look if the thing before the as, to make sure it is actually an array. Use var_dump to dump it.
Then fix the one where it isn't an array.
How to reproduce this error:
<?php
$skipper = "abcd";
foreach ($skipper as $item){ //the warning happens on this line.
print "ok";
}
?>
Make sure $skipper is an array.
Because, on whatever line the error is occurring at (you didn't tell us which that is), you're passing something to foreach that is not an array.
Look at what you're passing into foreach, determine what it is (with var_export), find out why it's not an array... and fix it.
Basic, basic debugging.
Try this.
if(is_array($value) || is_object($value)){
foreach($value as $item){
//somecode
}
}
I have written a code to view data but I'm having some problems.
From the code, I wrote it's viewing the data from one table which is the $details. But I also wanna view the data from the $detailsAns.
How can I do that? also, can I foreach two data from that two tables?
my code below:
public function queries($companyID, $entityType, $entityValue)
{
$data = [];
$details = DiraQuestion::where('company_id', $companyID)->where('eType', $entityType)->where('eVal', $entityValue)->get();
$detailsAns = DiraResponses::where('company_id', $companyID)->where('eType', $entityType)->where('eVal', $entityValue)->get();
foreach($details as $key => $detailsValue)
{
if(!array_key_exists($detailsValue->intent, $data))
{
$data[$detailsValue->intent] = [];
}
if(!array_key_exists($detailsValue->reply, $data[$detailsValue->intent]))
{
$data[$detailsValue->intent]['answer'][$detailsValue->reply] = $detailsValue->id;
}
if(!array_key_exists($detailsValue->queries, $data[$detailsValue->intent]))
{
$data[$detailsValue->intent]['question'][$detailsValue->queries] = $detailsValue->id;
}
}
ksort($data);
return view('AltHr.Chatbot.queries', compact('data','entityType','entityValue','companyID'));
}
so as you can see I can return the data from foreach for $details but now I want to return data for $detailsAns also. how can I do that?
my database structure:
table1:
table2:
so to get the data it first has to select the company id, eType, eVal, and intent so from that now i need to display the reply and queries.
The output that i want is as below:
So as you can see i can output the questions table in the foreach that i did. and if i change the foreach to $detailsAns then i display the reply.. but i want to view the both now
It isn't very clear from the data provided how the tables relate to each other. If the answer has the same id value as the question, it is easy to relate them by structuring the arrays so that they are keyed by the common value.
$data = [];
$details = DiraQuestion::where('company_id', $companyID)->where('eType', $entityType)->where('eVal', $entityValue)->get();
foreach ($details AS $datum) {
if (!isset($data[$datum->intent])) $data[$datum->intent] = ['question' => [], 'answer' => []];
$data[$datum->intent]['question'][$datum->id] = $datum->queries;
}
$detailsAns = DiraResponses::where('company_id', $companyID)->where('eType', $entityType)->where('eVal', $entityValue)->get();
foreach ($detailsAns AS $datum) {
if (!isset($data[$datum->intent])) $data[$datum->intent] = ['question' => [], 'answer' => []];
$data[$datum->intent]['answer'][$datum->id] = $datum->reply;
}
At this point, since you said that there is no relation between the data sets, just pass the data array to the view the way you already are:
return view('AltHr.Chatbot.queries', compact('data','entityType','entityValue','companyID'));
And loop through both elements of data, printing out values in the view:
#foreach ($data['approval-document']['question'] as $id=>$question)
<p>Question #{{ $id }}: {{ $question }}</p>
#endforeach
#foreach ($data['approval-document']['answer'] as $id=>$answer)
<p>Answer #{{ $id }}: {{ $answer }}</p>
#endforeach
I'm trying to create an html table based on the results from an array from a GET request. I have tried for loops and I have tried Java examples, but the results are always displayed as a long string (or if I return the results as dd($response) it only returns one row. I was wondering if there is a problem with the way format the array is returned:
{ "results":
[
{
"column1":"TEST1",
"column2":"DATADATADATA",
"time":"2017-02-27T16:25:03.1230000Z"
},
{
"column1":"TEST2",
"column2":"DATADATADATA",
"time":"2017-07-03T02:48:29.8300000Z"
},
{
"column1":"TEST3",
"column2":"DATADATADATA",
"time":"2017-07-19T15:09:27.0900000Z"}
]
}
This is one example I tried in PHP:
$reponse = array(print_r($response));
for ($i = 0; $i < count($reponse); $i++) {
for ($l = 0; $l < count($reponse[$i]); $l++) {
echo $reponse[$i][$l];
echo "<br/>";
};
};
Use json_decode() to convert JSON to an array:
$array = json_decode($data, true);
Then you'll be able to iterate over it:
#foreach ($array['results'] as $element)
{{ $element['column1'] }}
{{ $element['column2'] }}
{{ $element['time'] }}
#endforeach
Why am I getting this PHP Warning?
Invalid argument supplied for foreach()
Here is my code:
// look for text file for this keyword
if (empty($site["textdirectory"])) {
$site["textdirectory"] = "text";
}
if (file_exists(ROOT_DIR.$site["textdirectory"].'/'.urlencode($q).'.txt')) {
$keywordtext =
file_get_contents(ROOT_DIR.$site["textdirectory"].'/'.urlencode($q).'.txt');
}
else {
$keywordtext = null;
}
$keywordsXML = getEbayKeywords($q);
foreach($keywordsXML->PopularSearchResult as $item) {
$topicsString = $item->AlternativeSearches;
$relatedString = $item->RelatedSearches;
if (!empty($topicsString)) {
$topics = split(";",$topicsString);
}
if (!empty($relatedString)) {
$related = split(";",$relatedString);
}
}
$node = array();
$node['keywords'] = $q;
2
$xml = ebay_rss($node);
$ebayItems = array();
$totalItems = count($xml->channel->item);
$totalPages = $totalItems / $pageSize;
$i = 0;
foreach ($xml->channel->item as $item) {
$ebayRss =
$item->children('http://www.ebay.com/marketplace/search/v1/services');
if ($i>=($pageSize*($page-1)) && $i<($pageSize*$page)) {
$newItem = array();
$newItem['title'] = $item->title;
$newItem['link'] = buyLink($item->link, $q);
$newItem['image'] = ebay_stripImage($item->description);
$newItem['currentbid'] = ebay_convertPrice($item->description);
$newItem['bidcount'] = $ebayRss->BidCount;
$newItem['endtime'] = ebay_convertTime($ebayRss->ListingEndTime);
$newItem['type'] = $ebayRss->ListingType;
if (!empty($ebayRss->BuyItNowPrice)) {
$newItem['bin'] = ebay_convertPrice($item->description);
}
array_push($ebayItems, $newItem);
}
$i++;
}
$pageNumbers = array();
for ($i=1; $i<=$totalPages; $i++) {
array_push($pageNumbers, $i);
}
3
// get user guides
$guidesXML = getEbayGuides($q);
$guides = array();
foreach ($guidesXML->guide as $guideXML) {
$guide = array();
$guide['url'] = makeguideLink($guideXML->url, $q);
$guide['title'] = $guideXML->title;
$guide['desc'] = $guideXML->desc;
array_push($guides,$guide);
}
What causes this warning?
You should check that what you are passing to foreach is an array by using the is_array function
If you are not sure it's going to be an array you can always check using the following PHP example code:
if (is_array($variable)) {
foreach ($variable as $item) {
//do something
}
}
This means that you are doing a foreach on something that is not an array.
Check out all your foreach statements, and look if the thing before the as, to make sure it is actually an array. Use var_dump to dump it.
Then fix the one where it isn't an array.
How to reproduce this error:
<?php
$skipper = "abcd";
foreach ($skipper as $item){ //the warning happens on this line.
print "ok";
}
?>
Make sure $skipper is an array.
Because, on whatever line the error is occurring at (you didn't tell us which that is), you're passing something to foreach that is not an array.
Look at what you're passing into foreach, determine what it is (with var_export), find out why it's not an array... and fix it.
Basic, basic debugging.
Try this.
if(is_array($value) || is_object($value)){
foreach($value as $item){
//somecode
}
}