Inserting multiple arrays into same array section - php

I have a problem when I try to insert using one loop arrays into a specific place in the JSON. The app is designed to create a dictionary with main terms and their subterms (synonyms) . I succeeded to create the main terms but I can't add subterms. one entry contains main term and their translations and then subterms are encapsulated in "Subterms" sections with translations.
The final JSON file format I need is :
{
"glossary":{
"0":{
"id":4,
"English":{
"term":"accountability ",
"definition":"An obligation or willingness to use power"
}
},
"Subterms":[
{
"id":1,
"English":{
"term":"behavior change communication",
"definition":"The strategic use of communication approaches"
}
}
]
}
I want to insert multiple Arrays with a loop (in the example above is just English) into "Subterms" but no matter what I try is not letting me access that position.
PHP code:
<?PHP
$posts = array();
$subterms = array();
................
for($i = 0; $i < $val['maxentry']; $i++)
{
if ($i==1)
{
$dataheadenglish = $db->getRecFrmQry($queryheadenglish);
$headenglish = array (
'term'=> $dataheadenglish[0]['term'],
'definition'=> $dataheadenglish[0]['definition'],
)
$posts[] = array(
'id' => intval($dataheadenglish[0]['row']),
'English'=> $headenglish,
);
}
else
{
$dataenglish= $db->getRecFrmQry($queryenglish);
if(!empty($dataenglish))
{
$english= array (
'term'=> $dataenglish[0]['term'],
'definition'=> $dataenglish[0]['definition'],
);
}else $english=array();
// same for all languages to be inserted
$subterms[] = array(
'English'=> $english,
'Arabic'=> $arabic,
'Turkmen'=> $turk,
);
}
}
?>
I tried with :
$posts['Subterms'] = $subterms;
$posts['Subterms'][] = $subterms;
array_push($posts["Subterms"],$subterms);
but the subterms appears before posts(aka headterm)
{
"glossary": {
"Subterms": [
{
"English": [],
"Arabic": {
"term": "\u0627\u0644\u0645\u0633\u0627\u0621\u0644\u0629",
"definition": "",
"source": "",
}
},
"Kurdish_Badhini": [],
"Kurdish_Kurmanji": [],
"Kurdish_Sorani": [],
"Turkmen": []
}
],
"0": {
"English": {
"term": "accountability ",
"definition": "An obligation or willingness to use power responsibly and be held accountable for one's actions, both as individuals and as organizations.",
},
It should appear part of "0"
Thank you

In the beginning you showed a pattern of JSON you need, but at the end you said 'It should appear part of "0"'. Based on you example of JSON, I'll assume you wanted to say "past of".
If it got it right, the Subterms are being put before the "0" because it's exactly what you are telling it to do.
You are testing if $i is equal to 1, and because your for is starting with $i=0, your else will be happening before your if, so your subterms are being put in the array first.
if ($i==1) // because of this
{
// your code
}
else
{
// your code
}
My suggestion is to change this test from $i==1 to $i==0, so your if will happen first.

Related

Fragmenting incoming data with PHP Json

The form of the incoming json data:
{
"statusCode": 200,
"message": "success",
"result": [
{
"longitude": -87.06687,
"start_location_latitude": 20.63589,
"start_location_longitude": -87.06687,
"end_location_latitude": 20.63589,
"end_location_longitude": -87.06687,
"highlights": [
{
"title": "Oh Yes...Mezcal Shots",
"url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Mezcal_Shot.jpg"
},
{
"title": "Playa Del Carmen Beachfront",
"url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen-Beach_Punta_Esmeralda.jpg"
},
{
"title": "Visit the Market",
"url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen.jpg"
}
]
}
]
}
This incoming data is combined into a single line.
https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Mezcal_Shot.jpghttps://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen-Beach_Punta_Esmeralda.jpghttps://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen.jpg
But what I want to do is to get the first 4 of these data, for example, by throwing them into separate variables and using them. However, I was never able to do that.
My code:
foreach($UnlockData as $highlights)
{
foreach($highlights as $SingleImage)
{
if(strlen($SingleImage['url']) > 3) {
echo $SingleImage['url'];
}
}
}
This will return the first 4 highlights from each entry in result. I am using the json object vs array because I find using it as objects makes for easier to read code.
<?php
$json = json_decode($incomingJSON);
foreach ($json->result as $result) {
$ctr = 0 ;
foreach($result->highlights as $highlight) {
if (strlen($highlight->url) < 5) continue;
echo "<P>" . $highlight->title. " - " . $highlight->url;
$ctr ++;
if ($ctr>3) break;
}
}
If there is ever only one result then just get all the url from highlights (not clear why the strlen):
$urls = array_column($array['result'][0]['highlights'], 'url');
foreach($urls as $url) {
if(strlen($url) > 3) {
echo $url;
}
}
If there are multiple result then get all the highlights and then get all the url from that:
$urls = array_column(array_column($array['result'], 'highlights'), 'url']);

PHP need to count how many instaneces of specific value in array

I have a JSON file which structure looks like this (very simplified):
[
{
"customerId": "M12345",
"houses": [
{
"id": "OBJ12345_1731321200",
"status": {
"id": "4",
"name": "Sold"
}
],
"plots": [
{
"id": "OBJ12345_1771637082",
"status": {
"id": "4",
"name": "Sold"
}
],
"projects": [],
"farms": [],
"commercialPropertys": [],
"condominiums": [],
"foreignProperties": [],
"premises": []
}
]
I have figured out how to count how many "houses" or "plots" there is:
$content = file_get_contents('estateList/estateList.json');
$GetEstateList = json_decode($content);
count($GetEstateList[0]["houses"]);
count($GetEstateList[0]["plots"]);
BUT Trying to figure out using php how to count how many objects which have a condition status(id:4)
I think you will need to use a loop in order to count the objects, i would use a foreach loop, bellow is an example :
$count = 0;
foreach ( $GetEstateList[0] as $key => $value){
if (isset($value['status']) && $value['status']['id'] === "4") {
$count++;
}
}
First, you need to enter the GetEstateList array, then you need to do a cycle for each type (for now types showed are plots and houses), then you need another cycle, because each type is an array of elements and can have more than one estate.
So, try this code:
// Counter variable for condition expressed after (status == 4)
$counter = 0;
// Enter the array and get `customerId`, `houses` and `plots`,
// but we only need the types of estate, so only `houses` and `plots`, in this case
foreach ( $GetEstateList as $estate_array => $array_attr ) {
// We only need `houses` and `plots` (increasing algorithm performance)
if ( $array_attr == "houses" || $array_attr == "plots" ) {
// We're checking all types of estates (all `houses` and all `plots`)
foreach ( $array_attr as $type => $parameter ) {
// So, we can get `status` of every estate
if ( $parameter == "status") {
// And finally we can get `id` for each estate `status`
if ( $parameter["id"] == "4" ) {
$counter++;
}
}
}
}
}
Notice: the code above cannot work if the written JSON structure is too different from the original.
I figured it out myself...
Maybe not the "correct" way but it works! :)
Feel free to comment on any improvement or modifications...
$StatusCount = 0;
foreach ($GetEstateList[0] as $GetEstateType) {
foreach ($GetEstateType as $GetEstate) {
if ($GetEstate["status"]["id"] == "4") {
$StatusCount++;
}
}
}

PHP parsing a line from within a Json API page

I am trying to convert this script over from finding one set of variables eg(playtime_forever) to finding another variable eg(backpack_value)
if (!empty($data->response->games)) {
foreach ($data->response->games as $game) {
if ($game->appid == $game_id) {
$playtime = $game->playtime_forever;
if (($playtime < 5940) && ($playtime > 1)) {
$fh = fopen("final.".$timestamp.".txt", 'a') or die("Can't open file");
...
The page it originally parsed looked like this
http://pastebin.com/rnnCsijd
but will now be this. Pulled from here
http://backpack.tf/api/IGetUsers/v2/?&steamids=76561197992146126&format=json%27;
{
"response": {
"success": 1,
"current_time": 1369669066,
"players": {
"0": {
"steamid": "76561197992146126",
"success": 1,
"backpack_value": 36412.71,
"backpack_update": 1369630863,
"name": ":HIT: Bobo the Monkey Boy",
"notifications": 0
}
}
}
}
A small change but I am unable to make the script do what I want. If you could explain how to go about this and the steps behind it, it would be great. I have been trying for a while but I am unable to finish the script
To get the profiles as per your comment, use this code:
$profiles = array(); //init array so we can use $profiles[] later
$limitValue = 1000; //Limit value of backpack_value
foreach($data->response->players as $player) { // Loop thrugh all the players
if ($player->backpack_value < $limitValue) { // Check the backpack_value
$profiles[] = $player; // Assign the required players to a new array
}
}
var_dump($profiles); // Dump the array to browser for debugning

How to update (overwrite) a json file using php

[
{
"id" : 1,
"name" : "levin",
"description" : "some desc",
"size" : "100KG",
"actions" : {
"walking" : true,
"eating" : true
}
},
{
"id" : 2,
"name" : "clara",
"description" : "some desc",
"size" : "2000KG",
"actions" : {
"walking" : false,
"eating" : true
}
}
]
This is my person.json file. I like to update(overwrite) existing values. Am not found any useful questions regarding this.
i have a name "levin" i like to overwrite it to empty or "---". But its should only based through "id" .Following is my php code but its not working :(
public function api_put()
{
//print($this->put('id')); am getting here 2 value from other page
//print($this->put('action'));.
if($this->put('action') == "remove"){
$file = json_decode(file_get_contents("assets/json/person.json"));
$new_val = array();
$i = 0 ;
foreach ($file as $key => $value) {
if((string)$value->id == $this->put('id')) {
$data[] = (string)$value->name="--";(string)$value->description="--";
$new_val[$i] = $data;
$i++;
}
}
file_put_contents('assets/json/person.json', json_encode($new_val));
$message = array('id' => $this->put('id'), 'message' => 'Successfully updated!!');
$this->response($message, 200);
}
}
How can i overwrite a json value depend upon a particular id and with out change all other id data. am using codeigniter REST api. thanks in advance
A couple of things.
You don't need a $new_val array, you can just edit these resources in place.
PHP is weakly typed, so doing (string)$value->id == $this->put('id') is not necessary. The PHP engine will do this conversion for you.
Casting on the left side of the equal sign does nothing. (string)$value->description="--"; That statement has no effect.
This is poor form, in any programming language ... (string)$value->name="--";(string)$value->description="--"; Two statements doing two operations should be on two different lines.
General concept, your code should be easy to read. Space it out a little bit, let it breath. When you come back to your code years later you'll be glad that you did.
public function api_put()
{
if ($this->put('action') == 'remove')
{
$file = json_decode(file_get_contents('assets/json/person.json'));
foreach ($file as $key => $value)
{
if ($value->id == $this->put('id'))
{
$value->name = '--';
$value->description = '--';
}
}
file_put_contents('assets/json/person.json', json_encode($file));
$message = array('id' => $this->put('id'), 'message' => 'Successfully updated!!');
$this->response($message, 200);
}
}
There, isn't that much nicer?
I think you must need to loop like this to store all details
foreach ($file as $key => $value) {
if((string)$value->id == $this->put('id')) {
$value->name="--";(string)$value->description="--";
}
$new_val[$i] = $value;
$i++;
}

How to get different columns with JSON (PHP)?

I am very very new at PHP and I don't even know JSON. Also, I couldn't know how to express it in the question. My question is;
I need to make a JSON data with PHP with the data from database. So what my expected output is like;
{ "canFireAPICalls": true, "ads": { "servers": [ { "type": "OpenX", "apiAddress": "http://openx.openvideoads.org/openx/www/delivery/fc.php", } ], "schedule": [ { "zone": "5", "position": "pre-roll" }, { "zone": "33", "width": 450, "height": 50, "startTime": "00:00:05", "duration": "15" } ], } }
What I wrote in PHP is;
while ($doZones->fetch() && $row = $doZones->toArray()) {
$row_array['zone'] = $row['zoneid'];
$row_array['position'] = $row['delivery'];
if($row['delivery'] == 0 || $row['delivery'] == 1 || $row['delivery'] == 4 ){
$row_array['width'] = $row['width'];
$row_array['height'] = $row['height'];
}
array_push($return_arr,$row_array);
}
$resultJSON .=json_encode($return_arr);
And my output is
{ "canFireAPICalls": true, "ads": { "servers": [ { "type": "OpenX", "apiAddress": "http://openx.openvideoads.org/openx/www/delivery/fc.php", } ], "schedule":[{"zone":"3","position":"6"},{"zone":"2","position":"6"},{"zone":"4","position":"6"},{"zone":"5","position":"6"},{"zone":"6","position":"1","width":"468","height":"60"},{"zone":"7","position":"6","width":"468","height":"60"},{"zone":"8","position":"0","width":"120","height":"600"},{"zone":"9","position":"7","width":"120","height":"600"},{"zone":"10","position":"0","width":"120","height":"600"},{"zone":"11","position":"0","width":"728","height":"90"},{"zone":"12","position":"0","width":"120","height":"90"},{"zone":"13","position":"1","width":"468","height":"60"},{"zone":"14","position":"3","width":"468","height":"60"},{"zone":"15","position":"1","width":"560","height":"40"},{"zone":"16","position":"4","width":"468","height":"60"},{"zone":"17","position":"6","width":"468","height":"60"},{"zone":"18","position":"6","width":"468","height":"60"},{"zone":"19","position":"7","width":"468","height":"60"}] } }
If you noticed, even there shouldn't be width and height, there is. I only want the width and height when $row['delivery'] is 0,1 or 4. But, once it finds a value 0,1 or 4, then even if the next row is not 0,1 or 4, it prints width and height. Is there a way to fix this? I don't know any JSON and just started with PHP. Right now, I don't care about the missing tags like duration or writing pre-roll. I will take care of them after I fix this.
The problem is in your php. You don't reset the values of your array $row_array, so the first time the condition is true, the values of height and width are kept in the array.
You can fix it this way :
while ($doZones->fetch() && $row = $doZones->toArray()) {
$row_array['zone'] = $row['zoneid'];
$row_array['position'] = $row['delivery'];
if($row['delivery'] == 0 || $row['delivery'] == 1 || $row['delivery'] == 4 ){
$row_array['width'] = $row['width'];
$row_array['height'] = $row['height'];
}
array_push($return_arr,$row_array);
// Add this line to reset the array and reset width / height
$row_array = array();
}
$resultJSON .=json_encode($return_arr);

Categories