How to use unknown JSON key names as my table headers - php

I'm using Laravel framework.
I've got a table with some JSON I want to iterate over, I've cast the table to an array. This is the format;
{"Height": "#m", "Width": "#m", "Weight": {"now": "#kg", "previous": "#kg"}}
My controller returns the view;
$person = Person::find($ID);
$data = $person->tableJson;
return view('person.person_details', compact('person', 'data'));
And in the view itself:
#foreach ($data as $value)
Width: {{ $value->tableJson['Width'] }} <br>
Height: {{ $value->tableJson['Height'] }} <br>
Weight (now): {{ $value->tableJson['Weight']['now'] }} <br>
Weight (previous): {{ $value->tableJson['Weight']['previous'] }} <br>
<hr>
#endforeach
I have that working. The thing is I want to replace the hard coded titles (Width, Height, etc) with the keys in the JSON itself. That way I can (hopefully) dynamically populate a table without knowing what the JSON contains.

When looping your $data use actual keys in that:
$data = [0: ["Height" => "#m", "Width" => "#m", "Weight" => ["now" => "#kg", "previous" => "#kg"]]];
foreach ($data as row) {
foreach ($row as $header => $val) {
if (is_string($val)) {
echo "{$header}: {$val}<br/>";
} else {
foreach ($val as $type => $subVal) {
echo "{$header} ($type): {$subVal}<br/>";
}
}
}
echo "<hr/>";
}

Related

How can I user json to dispaly in laravel?

i tried to view data from database as per shown but get this error
$testjson = new TestJson ;
$testjson = $testjson->Where('id',2)->get();
return view('viewjson')->with('alldata',Json_decode($testjson));
user below code to view data
#foreach($alldata as $key => $value)
{{ $key }} - {{ $value }} <br>
#endforeach
can't get scope data
0 - {"id":2,"token":"2020-04-06 12:02:15","data":"{\"scope\":[\"volvo\",\"saab\",\"opel\",\"audi\"]}","created_at":"2020-04-06 12:02:15","updated_at":"2020-04-06 12:02:15"}
database
$testjson = new TestJson ;
$testjson = $testjson->Where('id',2)->get();
return response()->json(['data' => $testjson]);
If you are displaying in laravel view then no need to convert in json
$alldata = TestJson::find(2);
return view('viewjson', compact('alldata'));
And in laravel view
#foreach($alldata ?? [] as $key => $value)
#if($key == 'data')
#foreach(json_decode($value->data) ?? [] as $innerKey => $innerValue)
{{ $innerKey }} - {{ $innerValue}} <br>
#endforeach
#else
{{ $key }} - {{ $value }} <br>
#endif
#endforeach

Laravel : How to split/fetch the json nested elements in blade view?

When i am passing the below in view blade shows the entire Json structure fetching from mongo.
{!! $fees !!}
output :
[{"_id":"5e04a06ca445f78401a16d0a","University":[{"fees":"$200"},{"month":"June"}]}]
Now how to fetch the nested content.I want to show Fees = $200 and Month = June in the blade
Tried like this but result is 'blank' on the blade without any error. Is there any issue with the nested open/closing :[, which is just after 'University:' in the above JSOn input. Please suggest
#foreach ($fees as $value)
{{$content[] = $value->['University'] }}
#foreach ($content as $key)
<h1>{{ $key['fees'] }}</h1>
<h1>{{ $key['month'] }}</h1>
#endforeach
#endforeach
My earlier steps are given here :
Laravel not fetching result from mongodb
Edit(1) :
I tried like this so the structure on blade view.
<?php
$get_result = json_decode($fees, true);
#$get_result = implode(",", array_flatten($get_result));
#print_r($get_result);
#$get_result2 = json_encode($get_result, true);
echo "</br>";
print_r($get_result)
?>
output :
Array ([0] => Array ([_id] => 5e04a06ca445f78401a16d0a [University]
=> Array ([0] => Array ( [fees] => $200 ) [1] => Array ( [month] => June ) )))
Also,
<?php
echo htmlentities (print_r (json_encode ($fees), true));
?>
output:
"[{\"_id\":\"5e04a06ca445f78401a16d0a\",
\"University\":[{\"fees\":\"$200\"},{\"month\":\"June\"}]}]"
Also from Controller i tried as below:
..
public function getFees()
{
# database fetch test (with any one of the db query)
$fees = Finance::all();
$fees = Finance::where(['University.month' => 'June'])->get()->toArray();
$fees = Finance::where('University.month', 'June')->first();
$fees = Finance::where('University.month', 'June')->get();
# Return test (with any one of the return)
return view('tables')->with('fees', json_encode($fees, true));
return view('tables', compact('fees'));
return view('tables')->with(compact('fees'));
return view('tables')->with('fees', $fees);
}
..
Edit(2) :
in view blade i tried as below but getting exception as : Trying to get property 'fees' of non-object
<?php
$fees = json_decode($fees, true);
#echo "</br>";
#print_r($fees)
?>
#foreach ($fees[0] as $value)
#php $content = $value->University #endphp // or without #
#foreach ($content as $key)
<h1>{{ $key['fees'] }}</h1>
<h1>{{ $key['month'] }}</h1>
#endforeach
#endforeach
Edit(3) as per suggestion by Chandan.
<?php
$fees = json_decode($fees);
$univ = $fees[0]->University;
//print_r($univ);
foreach ($univ as $key => $value)
{
foreach($univ[$key] AS $k =>$v)
{
echo $k." " .$v;
}
}
?>
output :
fees $200month June
only thing the output is merges without comma separated.
Can I show them as below
fees = $200
month = June
or as a html
<td>{{$k}}</td><td>{{$v}}</td>
You can try this:
$fees = json_decode($fees);
$univ = $fees[0]->University;
//print_r($univ);
foreach ($univ as $key => $value) {
foreach($univ[$key] as $k =>$v){
echo $k .'= '.$v.' ';
}
}
It should be working as below:-
#foreach ($fees as $value)
{{$content[] = $value->['University'] }}
#if($content->['fees']!==null)
<h1>{{ $content['fees'] }}</h1>
#else
<h1>-</h1>
#endif
#if($content->['fees']!==null)
<h1>{{ $content['fees'] }}</h1>
#else
<h1>-</h1>
#endif
#endforeach

how to foreach data from same database with two tables laravel

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

GET request array to table in PHP

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

PHP: How to output dynamic multi dimension array values?

I have an array like this in PHP:
$array = array(
'main0' => array(
'level0' => array('0'=>'value_1'),
'level1' => array(
'0' => 'value_2',
'1' => 'value_3',
),
'level2' => array('0'=>'value_445')
),
'main1' => array(
'level0' => array('0'=>'value_1'),
'level1' => array('0'=>'value_12'),
'level2' => array(
'0' => 'value_2',
'1' => 'value_3',
),
'level3' => array('0'=>'value_5')
),
);
This array will be dynamic, to many mainkeys and levels, each level also have dynamic amount of values.
My problem is, I'm trying to echo each of the array level in select option html markup. I've tried foreach ($array[][] as $value) but with no luck. How to achieve this in PHP?
EDIT
Solved my problem using 3 foreach, might be not the cleanest solution but it works. My solution in blade php:
<?php $data = Product::GetCategories(); ?>
#if ($data != null)
#foreach ($data as $item)
<optgroup label="{{ $item[0][0] }}">
#foreach ($item as $level)
#foreach ($level as $v)
<option value="{{ $v }}">{{ $v }}</option>
#endforeach
#endforeach
</optgroup>
#endforeach
#endif
If you don't really care about manipulating the array items, and all you want is to see the result on screen, you may use: print_r($array);
If you do need to do something with the array items, then here is a recursive function(myRecursiveFunction), and a normal function that is executed on a non-array (myNormalFunction) to illustrate the process.
function myRecursiveFunction($array) {
foreach($array as $key=>$value) {
if(is_array($value)) {
myRecursiveFunction($value);
}
myNormalFunction($value);
}
}
For starters use something like DomDocument to manipulate html in php.
Other than that try:
foreach ($array as $key => $value ) {
print $key . " " . $value;
}
For further nesting keep is_array in mind, so now your code becomes
foreach ($array as $key => $value ) {
print $key . " " . $value;
if(is_array($value)) {
//do something with this array
}
}
You could do something with recursion here but its much better to use something like DomDocument which maintains a recursive tree for you to traverse with less code.
You can use recursion here.
Try this.
function traverse($array){
foreach($array as $item){
if(is_array($item)){
traverse($item);
}else echo $item . "<br/>";
}
}
traverse($array);
If you don't need dynamically go any deeper it would be like:
foreach($array as $mains) {
foreach($mains as $level){
var_dump($level);
}
}
If you want go deeper when $level has any children go with this:
function explore($array) {
foreach ($array as $child) {
if (gettype($child) === 'array')) {
explore($child);
} else {
echo $child;
}
}
}
// init
explore($array);

Categories