PHP foreach not saving all data from JSON - php

I'm pulling data from JSON array in php.
Everything works as expected but somewhere in the loop parts gets lost, it only pulls first one.
Please help.
Thank you very much.
Here is Json:
$json = '
{
"theId": "fB17",
"loadId": "82387T",
"description": "Short description",
"contact": "Name of person",
"contactinfo": "Phone number or email of contact person",
"pickupaddress": "Address",
"parts": [
{ "number": "655-2032B" },
{ "number": "655-2056" },
{ "number": "655-2056" },
{ "number": "300-85091" }
]
}';
PHP code:
$data = json_decode($json);
$theId .= $data->theId;
$loadId .= $data->loadId;
$description .= $data->description;
$contact .= $data->contact;
$contactinfo .= $data->contactinfo;
$pickupaddress .= $data->pickupaddress;
ALL ABOVE GET PULLED FROM JSON AND SAVED PROPERLY
Saving data
$obj = new ElggObject();
$obj->subtype = "load";
$obj->description = strip_tags($description);
$obj->title = $title.$theId.'-'.$loadId;
$obj->contact = $contact;
$obj->contactinfo = $contactinfo;
$obj->pickupaddress = $pickupaddress;
$guid = $obj->save();
Object is saved with basic info
Now going through "parts" data from Json
foreach ($data->parts as $core_title) {
// Getting "parts' value from Json
$titlename = $core_title->number;
//Now need to use that data and find existing entity with that title in Database
$dbprefix = elgg_get_config('dbprefix');
$options['joins'][] = "JOIN {$dbprefix}objects_entity oe ON oe.guid = e.guid";
$options['wheres'][] = "oe.title = '$titlename'";
$options['types'] = array('object');
$options['subtypes'] = array('core');
$options['limit'] = 1;
$entity = elgg_get_entities($options);
// I got that entity that matches the title
//Now get GUID of the entity
foreach ($entity as $o) {
$boxg = $o->guid;
}
// It works I get the GUID as $boxg but now need to save EACH $data->parts as annotation to database
$obj->annotate('cores', $boxg);
}
IT only grabs first one fron Json ( 655-2032B )and saves only that one.
If I do this it saves each $data->parts value not just first one:
foreach ($data->parts as $core_title) {
$titlename = $core_title->number;
$obj->annotate('cores', $titlename);
}

This code makes no sense:
//Now get GUID of the entity
foreach ($entity as $o) {
$boxg = $o->guid;
}
It goes through all items in $entity and keeps overwriting $boxg value without actually doing anything with the value.
The result of this foreach loop is that $boxg holds the GUID of the last item in $entity and only then this one single value used to annotate:
$obj->annotate('cores', $boxg);
Is this what you really wanted to do? Shouldn't the annotate method be used inside the foreach loop?
Apart from that it's hard to give you a clear answer because your code is rather obscure and not well explained.

Figured it out finally.
It was not foreach but what was in it.
Ended up making function that does database query to find existing entity with that title.
This is what I ended up with.
Thanks everyone for the help.
foreach ($data->parts as $core_title) {
$titlename = $core_title->number;
$entity = get_object_by_title('core',$titlename);
foreach ($entity as $o) {
$coreguidd = $o->guid;
$obj->annotate('cores', $coreguidd);
}
}

Related

how do json data become dynamic html tables using php?

how the json key is used as the table name, and displays data in the table, without the table name being created
{
"status": "sukses",
"title": "OK",
"img": "ok.jpg",
"data": {
"network": {
"technology": "No cellular connectivity",
"2g_bands": " N\/A",
"gprs": "No",
"edge": "No"
}
}
}
I want to make it like this
statuss title img technology 2g_bands gprs edge
sukses ok ok.jpg No cellular connectivity N\/A No No
with php Below, I am confused how to retrieve the json key to retrieve the name of the table I need to be dynamic
<?php
$Libs = new Library();
$result = $Libs->pilihmodel($idbrand,$idmodel);
if ($result->rowCount()>0) {
while ($datas = $result->fetch(PDO::FETCH_OBJ)) {
$datass = $datas->jsondetail;
$hasiljson = json_decode($datass, TRUE);
$binatang = array($hasiljson);
echo "<table>";
foreach ($binatang as $jenis) {
foreach ($jenis as $nama) {
echo "<td>$nama</td>";
}
}
echo "</table>";
}
You're about halfway there. Getting the keys is easy in a PHP foreach loop using $key => $value) syntax. Then you can, in parallel, build the header row and data row using the key and value from each field. Because of the structure of the JSON you also need to make a special case for the "data" object.
(If the structure is unpredictable you could make a recursive function which would traverse the structure and either print a field if it's a plain string, or find its children if it's another array, but that's probably overkill for what you're doing here. If you really need that though, please mention it.)
This will work:
$hasiljson = json_decode($datass, TRUE);
$header = "";
$body = "";
foreach ($hasiljson as $key => $value)
{
if ($key != "data")
{
$header .= "<td>$key</td>";
$body .= "<td>$value</td>";
}
else
{
foreach ($hasiljson["data"]["network"] as $key1 => $value1)
{
$header .= "<td>$key1</td>";
$body .= "<td>$value1</td>";
}
}
}
echo "<table><tr>$header</tr><tr>$body</tr></table>";
Demo: http://sandbox.onlinephpfunctions.com/code/8b61f2933b0ebf8a3ea1091c1e4474882e8c90a1

Append php loop data to JSON object

I need looped php data in an html template so I know it has something to do with JSON however not a JSON expert and cannot find much help in searching the web.
$uniqueFranchise_id = array_unique($franchise_id);
$dataArr = '[
{
"name": "Dylan",
"page_link": "https://mypage.com/"
}
]';
foreach($uniqueFranchise_id as $franchise)
{
$sqlFranchise = "select * from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
while($rowFranchise = $resultFranchise->fetch_assoc())
{
$dataArr = json_decode($data, TRUE);
$dataArr[] = "['name'=>'".$rowFranchise['name']."', 'page_link'=>'".$rowFranchise['page_link']."']";
//$json = json_encode($dataArr);
}
}
}
$json = json_encode($dataArr);
print_r($dataArr);
But it only appends one row. In fact it deleteds that data that's already in my dataArr and just adds one row from my loop? Maybe I'm approaching this situation completely wrong?
You set your $dataArr inside the while-loop. So each time the loop is runs, it will be overwritten. Also, it makes more sense and it's much more clear when you handle it as an array (or object) and afterwards convert it to JSON.
$dataArr = array(array('name' => 'Dylan', 'page_link' => 'https://mypage.com/'));
foreach($uniqueFranchise_id as $franchise)
{
$sqlFranchise = "select * from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
while($rowFranchise = $resultFranchise->fetch_assoc())
{
$dataArr[] = array('name' => $rowFranchise['name'], 'page_link' => $rowFranchise['page_link']);
}
}
}
$json = json_encode($dataArr);
echo $json;
You shouldn't be building the string up by yourself, you should build the data and then JSON encode the result (comments in code)...
$dataArr = '[
{
"name": "Dylan",
"page_link": "https://mypage.com/"
}
]';
// decode existing JSON to start array
$dataArr = json_decode($data, TRUE);
foreach($uniqueFranchise_id as $franchise)
{
// Read just the data you need from the table
$sqlFranchise = "select name, page_link from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
// Read all of the rows into an array
$newData = $resultFranchise->fetch_all(MYSQLI_ASSOC);
// Add in existing data
$dataArr = array_merge($dataArr, $newData);
}
}
// Now encode the list of elements into 1 string
echo json_encode($dataArr);
You should also look into prepared statements if this data is not trusted to stop SQL injection.

Create JSON response from Parsed XML PHP

I am parsing thorugh a eBay API response. I want to deliver this back to a website cleaner and easier to parse with JavaScript. I successfuly Parsed through the XML... but now turning that into JSON to resend back to the client is giving me some headaches.
NOTE: $resp is the response from eBay. It's their full length XML that is successfully parsed with the code below.
For example... $valueName could be Grade. And then I go into the next foreach loop and get the values for this. These values may be 10, 9.5, 9 etc.
Here is my PHP code.
$arrayName = array();
$arrayValue = array();
foreach($resp->aspectHistogramContainer->aspect as $name) {
$nameAspect = $name['name'];
//$arrayName["aspectName"] = $nameAspect;
foreach($name->valueHistogram as $value) {
$valueAspect = $value['valueName'];
//$arrayValue["aspectValue"] = $valueAspect;
}
//array_push($arrayName, $arrayValue);
}
echo json_encode($arrayName);
So, without me trying to create my own JSON, I am getting that I need. I echos results and it was similar to this...
NAME
----- Value
----- Value
----- Value
NAME
----- Value
NAME
etc etc
For a JSON response... Im looking for something like...
[
{
"name": "NAME",
"value": ["value", "value"]
}, {
"name": "name",
"value": ["value", "value"]
}
]
Any help and guidance would be greatly appreciated.
eBay's response is like this (there are A LOT more <aspect> and <valueHistogram>)
<getHistogramsResponse xmlns="http://www.ebay.com/marketplace/search/v1/services">
<ack>Success</ack>
<version>1.13.0</version>
<timestamp>2018-11-07T15:32:20.380Z</timestamp>
<aspectHistogramContainer>
<domainDisplayName>Baseball Cards</domainDisplayName>
<aspect name="Card Manufacturer">
<valueHistogram valueName="Ace Authentic">
<count>19</count>
</valueHistogram>
<valueHistogram valueName="American Caramel">
<count>2024</count>
</valueHistogram>
<valueHistogram valueName="APBA">
<count>10554</count>
</valueHistogram>
<valueHistogram valueName="Bazooka">
<count>8826</count>
</valueHistogram>
<valueHistogram valueName="Be A Player">
<count>17</count>
</valueHistogram>
<valueHistogram valueName="Bell Brand Dodgers">
<count>334</count>
To encode it (and assuming SimpleXML), then it's just a case of building each internal $aspect data array and then adding the values to it. I use (string) to ensure the data is not stored as a SimpleXMLElement, which can cause side effects...
$arrayName = array();
foreach($resp->aspectHistogramContainer->aspect as $name) {
$aspect = [ "name" => (string)$name['name']];
foreach($name->valueHistogram as $value) {
$aspect["value"][] = (string)$value['valueName'];
}
$arrayName[] = $aspect;
}
echo json_encode($arrayName);
with the sample XML, this gives...
[{"name":"Card Manufacturer","value":["Ace Authentic","American Caramel","APBA","Bazooka","Be A Player","Bell Brand Dodgers"]}]
Create one single array $resultArray and store values in it. By maintaining your current code structure with minimal changes, here is the updated code snippet,
$resultArray = array();
$i = 0; // Maintain Array Index value
foreach($resp->aspectHistogramContainer->aspect as $name) {
$resultArray[$i]["aspectName"] = (string)$name['name'];;
foreach($name->valueHistogram as $value) {
$resultArray[$i]["aspectValue"][] = (string)$value['valueName'];
}
$i++; // Increment array index to store next value
}
echo json_encode($resultArray);
$results = array();
// Parse the XML into a keyed array
foreach($resp->aspectHistogramContainer->aspect as $name) {
$nameAspect = (string) $name['name'];
$values = array();
foreach($name->valueHistogram as $value) {
$values[] = (string) $value['valueName'];
}
$results[$nameAspect] = $values;
}
// This keeps things simple - rewrite to the required JSON format
$outputForJSON = array();
foreach ($results as $name => $values) {
$outputForJSON[] = array(
"name" => $name,
"values" => $values
);
}
echo json_encode($outputForJSON);

Overwrite a json after modification in PHP

I make a modification in my json with this code:
$id = "hotel_name";
$value ="My Hotel";
$json = json_decode(file_get_contents('datas.json'));
$datas = $json->datas;
foreach ($datas as $category => $data) {
foreach ($data as $element) {
if($element->id==$id) {
$datas->$category->$element->$id = $value;
}
}
}
$newJson = json_encode($element);
file_put_contents('datas.json', $newJson);
But it do not put all the content in it.
How to solve it please ?
My json has the following:
{
"datas": {
"General": [
{
"field": "hotel_name",
"name": "My Hotel name"
}
]
}
}
You are accessing the $element variable, which contains only your inner most data
{
"field": "hotel_name",
"name": "My Hotel name"
}
If you want more of your data, you will have to reassign your outermost $datas variable and children with the newly updated $element variable. I'd recommend creating an empty variable to store the new data instead of altering the original copy.
You should be encoding datas, not just the last element, right?
// before
$newJson = json_encode($element);
// after
$newJson = json_encode($datas);
By the way, you might find it easier to work with the data if you convert it to an array rather than object.
$json = json_decode(file_get_contents('datas.json'), true);

Formatting json object using php

I'm trying to encode a json response using php, and having some trouble formatting it for use with ajax.
I'm basically trying to return an array of Rental objects, which each will include data for book, student, and teacher. Currently I'm using php to build objects like this...
while ($row = $result->fetch_array(MYSQLI_BOTH)) {
$obj = array();
// Build a book out of the results array, then push to the current object
$book = new Book();
$book->id = $row['book_id'];
$book->title = $row['title'];
$book->author = $row['author'];
$book->ar_quiz = $row['ar_quiz'];
$book->ar_quiz_pts = $row['ar_quiz_pts'];
$book->book_level = $row['book_level'];
$book->type = $row['type'];
$book->teacher_id = $row['teacher_id'];
array_push($obj, array('book' => $book));
// Build a student out of the results array, then push it to the current objects
$student = new Student();
$student->id = $row['student_id'];
$student->username = $row['student_username'];
$student->nicename = $row['student_nicename'];
$student->classroom_number = $row['classroom_number'];
array_push($obj, array('student' => $student));
// Build a teacher out of the results, push to current object
$teacher = new Teacher();
$teacher->id = $row['teacher_id'];
$teacher->username = $row['teacher_username'];
$teacher->nicename = $row['teacher_nicename'];
array_push($obj, array('teacher' => $teacher));
array_push($rentals, $obj);
}
mysqli_stmt_close($stmt);
return json_encode($rentals);
... building an $obj for each result, and then appending the whole $obj object to the end of $rentals, which is what I pass back in the end. Here is what the response looks like when I encode it to json:
[
[
{
"book":{
"id":113,
"title":"Book Test",
"author":"Test Test Author",
"ar_quiz":1,
"ar_quiz_pts":"10.0",
"book_level":"20.0",
"type":"Fiction",
"teacher_id":1
}
},
{
"student":{
"id":2,
"username":"studentnametest",
"classroom_number":2,
"nicename":"Student Name"
}
},
],
...
]
The problem here is that there is an extra {} around each of the book, student, and teacher objects, causing an extra step when trying to access in the javascript. For example, I think I have to use data[0].[0].book.title, when I really just want to be able to use data[0].book.title. How do I better structure this to fit my needs?
Don't add the additional array structure and you can simply change your array_push lines from
array_push($obj, array('book' => $book));
to
$obj['book'] = $book;

Categories