Add and update data in json file with php function - php

I want to control the data coming with the post with the function and update it if there is data, and add it if there is no data.
I am updating and adding with the following codes, but in the second addition, it both updates the existing information and adds the same information again.
I wonder where am I doing the mistake, can you help me?
$data = array('sure'=>'1', 'id'=>'38138373','t'=>'6', 's'=>'s3', 'p'=>'6');
function updateCart($data,$user_id,$cartid){
$updateCart = [];
$carts = getCart($user_id,$cartid);
foreach ($carts as $i => $cart) {
if($cart['id'] == $data['id'] && $cart['t'] == $data['t'] && $cart['s'] == $data['s']) {
$newp = $cart['p']+$data['p'];
$carts[$i]['p'] = $newp;
} else {
$carts[] = $data;
}
}
putJson($carts,$user_id,$cartid);
}
/* $carts */
[
{
"sure": "1",
"id": "38138373",
"t": "8",
"s": "s5",
"p": 6
},{
"sure": "1",
"id": "38138373",
"t": "6",
"s": "s3",
"p": 9
}
]
This is the result after the function.
[
{
"sure": "1",
"id": "38138373",
"t": "8",
"s": "s5",
"p": 6
},
{
"sure": "1",
"id": "38138373",
"t": "6",
"s": "s3",
"p": 9
},
{
"sure": "1",
"id": "38138373",
"t": "6",
"s": "s3",
"p": 12
},
{
"sure": "1",
"id": "38138373",
"t": "6",
"s": "s3",
"p": "3"
}
]
The file should be like this
[
{
"sure": "1",
"id": "38138373",
"t": "8",
"s": "s5",
"p": 6
},
{
"sure": "1",
"id": "38138373",
"t": "6",
"s": "s3",
"p": 15
}
]

The below code should work for you:
function updateCart($data, $user_id, $cartid){
$updateCart[] = $data;
$carts = getCart($data, $user_id, $cartid);
foreach ($carts as $cart) {
if( ($cart['id'] == $data['id']) && ($cart['t'] == $data['t']) &&
($cart['s'] == $data['s'])) {
$cart['p'] = $data['p'] + $cart['p'];
$data['p'] = $cart['p'];
$updateCart[0] = $cart;
}
$updateCart[] = $cart;
}
$updateCart[] = array_shift($updateCart);
return putJson($updateCart, $user_id, $cartid);
}
Let me know if this is okay. You should try and add break points at key stages in your code, to examine if the output is correct. How you do this is up to you, and your choices will vary depending on the framework you use etc. You could start with reading the PHP documentation about var_dump here.

Related

Is it possible to edit the elements of a json array to accomodate additional data/elements?

I'm retrieving data from a database and pushing it to arrays then use json_encode() to output in json format. I have ended up having the data in this format.
[
{
"category_id": "1",
"category_name": "Construction Materials"
},
{
"items": [
{
"id": "1",
"item_name": "Wire Mesh",
"price": "459",
"image_url": null
},
{
"id": "2",
"item_name": "Cement",
"price": "700",
"image_url": null
},
{
"id": "3",
"item_name": "Barbed Wire",
"price": "3000",
"image_url": null
},
{
"id": "4",
"item_name": "Iron sheet",
"price": "200",
"image_url": null
}
]
},
{
"category_id": "2",
"category_name": "Plumbing"
},
Here is what I want to achieve:
[
{
"category_id": "1",
"category_name": "Construction Materials"
"items": [
{
"id": "1",
"item_name": "Wire Mesh",
"price": "459",
"image_url": null
},
{
"id": "2",
"item_name": "Cement",
"price": "40",
"image_url": null
},
{
"id": "3",
"item_name": "Barbed Wire",
"price": "3000",
"image_url": null
},
{
"id": "4",
"item_name": "Iron sheet",
"price": "200",
"image_url": null
}
]
},
{
"category_id": "2",
"category_name": "Plumbing"
},
How can I achive this in php. Is it possible to edit the contents of the main array? how can I add "items" after "category_name"
Regards..
$array = json_decode($yourJson);
$arrayLength = count($array);
$finalArray = [];
for ($i=0; $i < $arrayLength; $i+=2) {
$finalArray[] = $array[$i] + $array[$i + 1];
}
$backToJson = json_encode($finalArray);
Alternative to Mattijs's answer.
function get_first_property($object) {
$properties = array_keys(get_object_vars($object));
return reset($properties);
}
function object_merge($object1, $object2) {
return (object) array_merge((array) $object1, (array) $object2);
}
// loop through each of the array objects
$previous_first_property = null;
foreach ($array as $i => $object) {
$first_property = get_first_property($object);
// merge if the 1st property is "items", and the previous 1st was "category_id"
if ($first_property == "items" && $previous_first_property == "category_id") {
$array[$i - 1] = object_merge($array[$i - 1], $array[$i]);
unset($array[$i]);
}
$previous_first_property = $first_property;
}

How can I access index with # in json

I need to get properties from this "#attributes"
{
"#attributes": {
"docid": "1082530207018916577"
},
"track": [
{
"#attributes": {
"id": "0",
"name": "",
"lang_code": "da",
"lang_original": "Dansk",
"lang_translated": "Danish"
}
},
{
"#attributes": {
"id": "5",
"name": "",
"lang_code": "nl-BE",
"lang_original": "Nederlands (België)",
"lang_translated": "Dutch (Belgium)"
}
},
{
"#attributes": {
"id": "2",
"name": "",
"lang_code": "en-GB",
"lang_original": "English (United Kingdom)",
"lang_translated": "English (United Kingdom)",
"lang_default": "true"
}
},
{
"#attributes": {
"id": "1",
"name": "",
"lang_code": "de-DE",
"lang_original": "Deutsch (Deutschland)",
"lang_translated": "German (Germany)"
}
},
{
"#attributes": {
"id": "4",
"name": "",
"lang_code": "id",
"lang_original": "Indonesia",
"lang_translated": "Indonesian"
}
},
{
"#attributes": {
"id": "6",
"name": "",
"lang_code": "pl",
"lang_original": "Polski",
"lang_translated": "Polish"
}
},
{
"#attributes": {
"id": "7",
"name": "",
"lang_code": "pt-BR",
"lang_original": "Português (Brasil)",
"lang_translated": "Portuguese (Brazil)"
}
},
{
"#attributes": {
"id": "3",
"name": "",
"lang_code": "es-419",
"lang_original": "Español (Latinoamérica)",
"lang_translated": "Spanish (Latin America)"
}
},
{
"#attributes": {
"id": "8",
"name": "",
"lang_code": "sv",
"lang_original": "Svenska",
"lang_translated": "Swedish"
}
}
]
}
My code:
$xml = simplexml_load_file('http://video.google.com/timedtext?type=list&v='.$video->id_youtube);
$json = json_encode($xml);
$result_array = json_decode($json, TRUE);
$res = "";
foreach ($result_array['track']['#attributes'] as $track) {
$res .= $track['lang_code'].'<br>';
}
return $res;
PHP or maybe Laravel is not recognizing the index "#attributes", reporting:
Undefined index: #attributes
How can I get the lang_codes?
$result_array['track'] is an array of objects.
You have to do
foreach($result_array['track'] as $track) {
$track = (array)$track;
$res .= $track['#attributes']['lang_code'].'<br>';
}

How to get parent array element in PHP with recursive function

I have PHP code as shown below which will print:
id:3deep:2path:image31.jpg
id:4deep:2path:image32.jpg
when I input deep = 2. However I would like to get parent array of this deep which is id = 2. Is there any way that I can do this?
Note:
Please see the result when I input deep as below:
> Deep = 1
ID = 0
ID = 1
ID = 2
ID = 7
ID = 8
> Deep = 2
ID = 2
ID = 3
ID = 4
> Deep = 3
ID = 4
ID = 5
ID = 6
Please check my code online.
PHP:
$obj = '{
"images": {
"deep": "1",
"id": "0",
"path": "image1.jpg",
"image": [
{
"deep": "1",
"id": "1",
"coordinate": "(x,y),(x,y)",
"path": "image2.jpg"
},
{
"deep": "1",
"id": "2",
"coordinate": "(x,y),(x,y)",
"path": "image3.jpg",
"image": [
{
"deep": "2",
"id": "3",
"coordinate": "(x,y),(x,y)",
"path": "image31.jpg"
},
{
"deep": "2",
"id": "4",
"coordinate": "(x,y),(x,y)",
"path": "image32.jpg",
"image": [
{
"deep": "3",
"id": "5",
"coordinate": "(x,y),(x,y)",
"path": "image321.jpg"
},
{
"deep": "3",
"id": "6",
"coordinate": "(x,y),(x,y)",
"path": "image322.jpg"
}
]
}
]
},
{
"deep": "1",
"id": "7",
"coordinate": "(x,y),(x,y)",
"path": "image4.jpg"
},
{
"deep": "1",
"id": "8",
"coordinate": "(x,y),(x,y)",
"path": "image5.jpg"
}
]
}
}';
$objArray = json_decode($obj,true);
$deep = 2;
$arr = all($objArray['images'], $deep);
display($arr);
function all($a, $d){
$temp = array();
if(is_array($a)){
foreach($a as $v){
all($v, $d);
}
if(isset($a['deep']) && $d == $a['deep']){
$temp['id'] = $a['id'];
$temp['deep'] = $a['deep'];
$temp['path'] = $a['path'];
$s =
'id:'.$a['id'].
'deep:'.$a['deep'].
'path:'.$a['path'];
display($s);
}
}
return ;
}
function display($a){
echo "<pre>";
print_r($a);
echo "</pre>";
}
Idk exactly what you want, but I changed your code a bit to filter in a nicer way and it adds the parent key to each $image so you can reference that afterwards.
You can set the $deep = null paramater to just add the parent to the image instead of filtering.
I hope you don't mind I changed the code style a bit, easier to read ( I hope :D )
Here's the code within phpfiddle: http://phpfiddle.org/main/code/8q0-c43
<?php
$obj = '{
"images": {
"deep": "1",
"id": "0",
"path": "image1.jpg",
"image": [
{
"deep": "1",
"id": "1",
"coordinate": "(x,y),(x,y)",
"path": "image2.jpg"
},
{
"deep": "1",
"id": "2",
"coordinate": "(x,y),(x,y)",
"path": "image3.jpg",
"image": [
{
"deep": "2",
"id": "3",
"coordinate": "(x,y),(x,y)",
"path": "image31.jpg"
},
{
"deep": "2",
"id": "4",
"coordinate": "(x,y),(x,y)",
"path": "image32.jpg",
"image": [
{
"deep": "3",
"id": "5",
"coordinate": "(x,y),(x,y)",
"path": "image321.jpg"
},
{
"deep": "3",
"id": "6",
"coordinate": "(x,y),(x,y)",
"path": "image322.jpg"
}
]
}
]
},
{
"deep": "1",
"id": "7",
"coordinate": "(x,y),(x,y)",
"path": "image4.jpg"
},
{
"deep": "1",
"id": "8",
"coordinate": "(x,y),(x,y)",
"path": "image5.jpg"
}
]
}
}';
$objArray = json_decode($obj, true);
function filter_deep(array $input, $deep = null, $parent = null) {
// store $results so we can return it
$result = array();
// loop over the $input
foreach ($input as $image) {
// set the parent passed alogn
$image['parent'] = $parent;
// add $image to $result if 'deep' == $deep
if ($deep === null || $image['deep'] == $deep) {
$result[] = $image;
}
// if the $image contains more child images recursively run this function again
// and merge the result with what we already have
if (isset($image['image']) && is_array($image['image'])) {
$result = array_merge($result, filter_deep($image['image'], $deep, $image));
}
}
return $result;
}
function display_image($image) {
return "id:{$image['id']} deep:{$image['deep']} path:{$image['path']} parent_id:{$image['parent']['id']} <br />\n";
}
// loop over the images that have deep == 2 and display them
foreach (filter_deep(array($objArray['images']), 2) as $image) {
echo display_image($image);
}
?>

php json_encode formatting results?

I have:
$all = array(
array('id'=>1, 'cat'=>'Main','type'=>'Name0'),
array('id'=>2, 'cat'=>'Main','type'=>'Name1'),
array('id'=>3, 'cat'=>'Main','type'=>'Name3'),
array('id'=>4, 'cat'=>'Main','type'=>'Name4'),
array('id'=>5, 'cat'=>'Secondary','type'=>'Name5'),
array('id'=>6, 'cat'=>'Secondary','type'=>'Name6'),
array('id'=>7, 'cat'=>'Secondary','type'=>'Name7'),
array('id'=>8, 'cat'=>'Other','type'=>'Name8'),
array('id'=>9, 'cat'=>'Other','type'=>'Name9'),
array('id'=>10, 'cat'=>'Other','type'=>'Name10'),
array('id'=>11, 'cat'=>'Other','type'=>'Name11'),
);
$result = array();
foreach($all as $array){
$result[$array['cat']][] = array('id'=>$array['id'],'type'=>$array['type']);
}
$json_type = json_encode($result);
Which returns:
{"Main":[{"id":"1","type":"name1"},{"id":"2","type":"name2"},{"id":"3","type":"name3"},{"id":"4","type":"name4"}],"Secondary":[{"id":"5","type":"name5"},{"id":"6","type":"name6"},{"id":"7","type":"name7"}],"Other":[{"id":"8","type":"name8"},{"id":"9","type":"name9"},{"id":"10","type":"name10"},{"id":"11","type":"name11"}]}
But I need it to return as:
[
{
"text": "Main",
"children": [
{
"id": "1",
"text": "name1"
},
{
"id": "2",
"text": "name2"
},
{
"id": "3",
"text": "name3"
},
{
"id": "4",
"text": "name4"
}
]
},
{
"text": "Secondary",
"children": [
{
"id": "5",
"text": "name5"
},
{
"id": "6",
"text": "name6"
},
{
"id": "7",
"text": "name7"
}
]
},
{
"text": "Other",
"children": [
{
"id": "8",
"text": "name8"
},
{
"id": "9",
"text": "name9"
},
{
"id": "10",
"text": "name10"
},
{
"id": "11",
"text": "name11"
}
]
}
]
To work with the select2 JQuery plugin, I'm working with.
the 'children' name doesn't matter, I think that's just a placeholder so it gets parsed correctly. I'm not sure how I would go about it, I've been trying str_replace() but even that hasn't been working out so great.
I would to it in 2 loops. The first one to group results by category, the 2nd one to format it to fit your needs:
$temp = array();
foreach($all as $array){
if (!isset($temp[$array['cat']])) {
$temp[$array['cat']] = array();
}
$temp[$array['cat']][] = array('id'=>$array['id'], 'type'=>$array['type']);
}
$result = array();
foreach ($temp as $key=>$value) {
$result[] = array('text'=>$key, 'children'=>$value);
}
echo json_encode($result);
This produces the following output:
[{"text":"Main","children":[{"id":1,"type":"Name0"},{"id":2,"type":"Name1"},{"id":3,"type":"Name3"},{"id":4,"type":"Name4"}]},{"text":"Secondary","children":[{"id":5,"type":"Name5"},{"id":6,"type":"Name6"},{"id":7,"type":"Name7"}]},{"text":"Other","children":[{"id":8,"type":"Name8"},{"id":9,"type":"Name9"},{"id":10,"type":"Name10"},{"id":11,"type":"Name11"}]}]

JSON decoding array

I have this JSON code:
{
"phrases": [
{
"phrases": [
{
"id": "33",
"text": "sasdsad",
"date": "2012-03-14 20:28:45",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
},
{
"id": "32",
"text": "que ondaa\r\n",
"date": "2012-03-14 20:27:45",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
},
{
"id": "31",
"text": "dsadssadsad",
"date": "2012-03-14 20:27:35",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
}
],
"details": {
"success": "true",
"phrase_id": "",
"phrase_text": "",
"phrase_date": ""
}
}
I don't really know what to do. I get some phrases vía MySQL, and pushes them to an array. This array is json_encoded() and gets printed.
$sth = $sql;
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
$sth = $sql;
$data = array(
"success" => "true",
"phrase_id" => "",
"phrase_text" => "",
"phrase_date" => "",
);
print json_encode($rows).json_encode($data);
and with jQuery I was trying to parse it, but I can't. This is the main problem.
function getPhrases(order,limit,last){
var req_url = ...;
$.getJSON(req_url, function(data) {
$.each(data.phrases, function(i, data) {
appendPhrase(data.text);
lastid = data.id;
});
$.each(data.details, function(i, data) {
$("#phrases-count").html(data.totalcount);
});
});
}
PS: I was doing this with "echo" but got some problems.
{
"phrases": [
{
"id": "33",
"text": "sasdsad",
"date": "2012-03-14 20:28:45",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
},
{
"id": "32",
"text": "que ondaa<br />",
"date": "2012-03-14 20:27:45",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
},
{
"id": "31",
"text": "dsadssadsad",
"date": "2012-03-14 20:27:35",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
}
],
"details": [
{
"totalcount": "3",
"logged_in": "false"
}
]
}
You can't simply combine these JSON arrays:
print json_encode($rows).json_encode($data);
Try this (attempt 2):
print json_encode( array('phrases' => $rows, 'details' => $data) );

Categories