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
Related
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/>";
}
My Script :
<?php
$values='Product1,54,3,888888l,Product2,54,3,888888l,';
$exp_string=explode(",",$values);
$f=0;
foreach($exp_string as $exp_strings)
{
echo "".$f." - ".$exp_string[$f]." ";
if ($f%3==0)
{
print "<br><hr><br>";
}
$f++;
}
?>
With this code i want show data inside loop, the idea it´s show all information in groups the elements in each group it´s 4 elements and must show as this :
Results :
Group 1 :
Product1,54€,3,green
Group 2:
Product2,56€,12,red
The problem it´s i don´t know why, don´t show as i want, and for example show separate some elements and not in group, thank´s , regards
It looks like you are trying to combine elements of a for loop and a foreach loop.
Here is an example of each, pulled from the php manual:
For Loop
for($index = 0, $index < size($array), $index++ {
//Run Code
//retrieve elements from $array with $array[$index]
}
Foreach
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
It's hard for me to understand what your input looks like. If you post an example of $exp_strings, I could be of better assistance. But from the sound of your question, if $exp_strings is multidimensional if you need to loop through groups of items, you could try nesting one loop inside another loop like so:
$groups_of_data = array(array(...), array(...), array(...));
for($i = 0, $i < size($groups_of_data), $i++) {
$group = $i;
for($j = 0, $j < size($groups_of_data[$i]), $j++) {
// print out data related to group $i
}
}
This is really all guesswork on my part though as I can't see what your input string/array is. Can you post that? Maybe I can be of more help.
here is code i worked out. it was kind of since i did't know what object $exp_string is. if it's a string you should tokenize it, but i think it's array from database. there was another problem, with your code where it tries to output $exp_string[$f] it should be $exp_strings what changes in the loop.
my code
$exp_string=array("Product"=>54,"price"=>3,"color"=>"green");
$f=0;
foreach($exp_string as $key => $exp_strings)
{
if($f%3==0)
{
print "<br><hr><br>";
echo "Product ".$exp_strings."<br> ";
}
else if($f%3==1)
{
echo "Price ".$exp_strings."<br> ";
}
else if($f%3==2)
{
echo "Color ".$exp_strings."<br> ";
}
$f++;
}
hope it's any help, maybe not what you wanted.
$values='Product1,1,2,3,Product2,1,2,3,Product3,1,2,3';
$products = (function($values) {
$exp_string = explode(',', $values);
$products = [];
for ($i=0; $i+3<count($exp_string); $i+=4) {
$product = [
'title' => $exp_string[$i],
'price' => $exp_string[$i+1],
'color' => $exp_string[$i+2],
'num' => $exp_string[$i+3],
];
array_push($products, $product);
}
return $products;
})($values);
/* var_dump($products); */
foreach($products as $product) {
echo "{$product['title']},{$product['price']},{$product['color']},{$product['num']}<br>";
}
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']))
I have an array of People objects. I'm sending them to PHP but the way to get my objects back in PHP so I can manipulate them seems convoluted. Here's what I have, but it doesn't seem to return anything back to my AJAX Call. Right now I just have 1 Person Object in my array but I want to make sure everything is fine before I advance. In short, when I decode my JSON shouldn't it convert it to an Object in PHP? In the end I want an array of PHP objects that are People
Jquery
var people = new Array();
var person = new Person("Michael", "Jackson", 50);
localStorage.setItem(person.firstName + " " + person.lastName, JSON.stringify(person));
function Person(firstName, lastName, age)
{
this.firstName=firstName;
this.lastName=lastName;
this.age=age;
}
function getStorage(){
var tempPerson;
for(var i = 0; i < localStorage.length; i++)
{
tempPerson = $.parseJSON(localStorage.getItem(localStorage.key(i)));
people.push(tempPerson);
}
}
function getPeople(){
$.post(
"people.php",
{people : people},
function(data)
{
alert(data);
}
);
}
getStorage();
getPeople();
PHP
<?php
$personObj = Array();
$people = $_POST['people'];
for($i = 0; $i < count($people); $i++)
{
foreach($people[$i] as $person)
{
$streamObj = json_decode($person);
}
}
echo $personObj->$firstName;
In addition to making the change suggested by #Even Hahn, you need to change the data you are posting as follows:
$.post(
"people.php",
{people : JSON.stringify(people)},
function(data)
{
alert(data);
}
);
This way a single name/value pair is posted. The name is "people" and the value is a JSON encoded string of the array of Person objects.
Then when you call the following in the PHP code, you are decoding that JSON encoded string into an array on the PHP side.
$people = json_decode($_POST['people']);
I also see where you assign $personObj to an array, but I don't see where you put anything in the array.
Try moving your JSON decoding in your PHP:
$personObj = Array();
$people = json_decode($_POST['people']);
for($i = 0; $i < count($people); $i++)
{
foreach($people[$i] as $person)
{
$streamObj = $person;
}
}
echo $personObj->$firstName;
This is because $_POST['people'] is a JSON string which needs to be decoded.
Perhaps the PHP codes should be look like this:
<?php
$personObj = Array();
$people = $_POST["people"];
foreach($people as $p)
{
$val = str_replace("\\","",$p);
$personObj = json_decode($val);
}
echo $personObj->firstName;
?>
A server sends me a $_POST request in the following format:
POST {
array1
{
info1,
info2,
info3
},
info4
}
So naturally, I could extract the info# very simply with $_POST['#info'].
But how do I get the the three info's in the array1?
I tried $_POST['array1']['info1'] to no avail.
Thanks!
a:2: {s:7:"payload";s:59:"{"amount":25,"adjusted_amount":17.0,"uid":"jiajia"}";s:9:"signature";s:40:"53764f33e087e418dbbc1c702499203243f759d4";}
is the serialized version of the POST
Use index notation:
$_POST['array1'][0]
$_POST['array1'][1]
$_POST['array1'][2]
If you need to iterate over a variable response:
for ($i = 0, $l = count($_POST['array1']); $i < $l; $i++) {
doStuff($_POST['array1'][$i]);
}
This more or less takes this shape in plain PHP:
$post = array();
$post['info'] = '#';
$post['array1'] = array('info1', 'info2', 'info3');
http://codepad.org/1QZVOaw4
So you can see it's really just an array in an array, with numeric indices.
Note, if it's an associative array, you need to use foreach():
foreach ($_POST['array1'] as $key => $val) {
doStuff($key, $val);
}
http://codepad.org/WW7U5qmN
try
$_POST['array1'][0]
$_POST['array1'][1]
$_POST['array1'][2]
You can simply use a foreach loop on the $_POST
foreach($_POST["array1"] as $info)
{
echo $info;
}
or you can access them by their index:
for($i = 0; $i<sizeof($_POST["array1"]); $i++)
{
echo $_POST["array1"][$i];
}