add/combine json array to array in JSON file php - php

I have been trying to solve this problem for the better part of two days with no success. I am trying combine/add to a json array that is stored in a .json file on my server using php.
This is a short version of what I'm trying to combine.
box.json:
[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"}]
posted json:
[{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]
This is what I need.
[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"},
{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]
This is what I get. (an array inside an array)
[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"},
[{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]]
This is my code:
<?php
$sentArray = $_POST['json'];
$boxArray = file_get_contents('ajax/box.json');
$sentdata = json_decode($sentArray);
$getdata = json_decode($boxArray);
$sentdata[] = $getdata; /* I also tried array_push($sentdata, $getdata); */
$json = json_encode($sentdata);
$fsize = filesize('ajax/box.json');
if ($fsize <= 5000){
if (json_encode($json) != null) { /* sanity check */
$file = fopen('ajax/box.json' ,'w+');
fwrite($file, $json);
fclose($file);
}else{
/*rest of code*/
}
?>
Please help my sanity is starting to come in to question.

here is your problem
$sentdata[] = $getdata;
use foreach
foreach($getdata as $value)
$sentdata[] = $value;
UPDATE:
but i think you need this for $sentdata not $getdata
foreach($senttdata as $value)
$getdata[] = $value;
then put $getdata to your file.

$box = json_decode(file_get_contents('ajax/box.json'));
$posted = json_decode($_POST['json']);
$merge = array_merge ((array)$box,(array)$posted);
Casting (array) prevent error if $box or $posted become null or false, it will be an empty array

Instead of this:
$sentdata[] = $getdata; /* I also tried array_push($sentdata, $getdata); */
Try:
$combinedData = array_merge($sentData, $getData);
$json = json_encode($combinedData);
By using array_merge you're combining the arrays into one instead of adding one array as a value into the other.
Note that I changed the name of your resulting data - try to avoid variables with the same name and different capitalization, it will make things much easier to understand (for you and for future developers supporting your code).
Cheers

Related

Creating a function that takes arguments and passes variables

I am creating a script that will locate a field in a text file and get the value that I need.
First used the file() function to load my txt into an array by line.
Then I use explode() to create an array for the strings on a selected line.
I assign labels to the array's to describe a $Key and a $Value.
$line = file($myFile);
$arg = 3
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
This works fine but that is a lot of code to have to do over and over again for everything I want to get out of the txt file. So I wanted to create a function that I could call with an argument that would return the value of $key and $val. And this is where I am failing:
<?php
/**
* #author Jason Moore
* #copyright 2014
*/
global $line;
$key = '';
$val = '';
$myFile = "player.txt";
$line = file($myFile); //file in to an array
$arg = 3;
$Character_Name = 3
function get_plr_data2($arg){
global $key;
global $val;
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
return;
}
get_plr_data2($Character_Name);
echo "This character's ",$key,' is ',$val;
?>
I thought that I covered the scope with setting the values in the main and then setting them a global within the function. I feel like I am close but I am just missing something.
I feel like there should be something like return $key,$val; but that doesn't work. I could return an Array but then I would end up typing just as much code to the the info out of the array.
I am missing something with the function and the function argument to. I would like to pass and argument example : get_plr_data2($Character_Name); the argument identifies the line that we are getting the data from.
Any help with this would be more than appreciated.
::Updated::
Thanks to the answers I got past passing the Array.
But my problem is depending on the arguments I put in get_plr_data2($arg) the number of values differ.
I figured that I could just set the Max of num values I could get but this doesn't work at all of course because I end up with undefined offsets instead.
$a = $cdata[0];$b = $cdata[1];$c = $cdata[2];
$d = $cdata[3];$e = $cdata[4];$f = $cdata[5];
$g = $cdata[6];$h = $cdata[7];$i = $cdata[8];
$j = $cdata[9];$k = $cdata[10];$l = $cdata[11];
return array($a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l);
Now I am thinking that I can use the count function myCount = count($c); to either amend or add more values creating the offsets I need. Or a better option is if there was a way I could generate the return array(), so that it would could the number of values given for array and return all the values needed. I think that maybe I am just making this a whole lot more difficult than it is.
Thanks again for all the help and suggestions
function get_plr_data2($arg){
$myFile = "player.txt";
$line = file($myFile); //file in to an array
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
return array($key,$val);
}
Using:
list($key,$val) = get_plr_data2(SOME_ARG);
you can do this in 2 way
you can return both values in an array
function get_plr_data2($arg){
/* do what you have to do */
$output=array();
$output['key'] =$key;
$output['value']= $value;
return $output;
}
and use the array in your main function
you can use reference so that you can return multiple values
function get_plr_data2($arg,&$key,&$val){
/* do job */
}
//use the function as
$key='';
$val='';
get_plr_data2($arg,$key,$val);
what ever you do to $key in function it will affect the main functions $key
I was over thinking it. Thanks for all they help guys. this is what I finally came up with thanks to your guidance:
<?php
$ch_file = "Thor";
$ch_name = 3;
$ch_lvl = 4;
$ch_clss = 15;
list($a,$b)= get_char($ch_file,$ch_name);//
Echo $a,': ',$b; // Out Puts values from the $cdata array.
function get_char($file,$data){
$myFile = $file.".txt";
$line = file($myFile);
$cdata = preg_split('/\s+/', trim($line[$data]));
return $cdata;
}
Brand new to this community, thanks for all the patience.

Using array from header in another page

Ok so I have an array "$landing" in my header.php, then in my page.php I include the header.php but for some reason when I call the 'Name' field in the array in the page.php: echo $landing['Name']; it just doesn't work.
this is how the array is being filled up, and calling it in the header works perfectly.
$landing = array();
while ($row = mysql_fetch_array($result)) {
$str = strtolower($row['Name']);
if ($str == $name) {
$landing = $row;
}
}
To clarify, $row and $landing are both arrays, and both have multiple fields 'Name' 'Color' 'Info'.
What am I doing wrong here? Do I need to make it global somehow or what's going on?
The original code works somehow, now as the OP said in a comment.
But my old tips still hold:
Consider using MySQLi or PDO instead of the deprecated MySQL extension!
Why do you compare the dataset's column value on the client-side? You can do this on the MySQL side, it'll be faster!
You are, as ComFreek correctly stated, turning $landing into a string. Instead, if you're trying to add an entry to the landing array, use [] brackets which mean "add into new entry".
$landing = array();
while ($row = mysqli_fetch_array($result)) {
$str = strtolower($row['Name']);
if ($str == $name) {
$landing[] = $row;
}
}
I cant comment LS97 post, anyway you want to use $landing["Name"] you edit LS97 code into this:
$landing = array();
while ($row = mysqli_fetch_array($result)) {
$str = strtolower($row['Name']);
if ($str == $name) {
$landing["name"] = $row;
}
}
If you want to use multiple names, LS97 code is fine.
The problem is what they said. (Using $landing = $row, landing will be a string.)

Re encode json after file manipulation

I'm having some problems re-encoding the json back to it's format. What I'm trying to achieve is, on a .json file upload, modify it to meet certain standards.
The problem is when I try to modify the image src on the file an encode it back to json, nevertheless the array in the foreach loop prints out correctly, the new file is generated without any content!
Glad if you could give me a little help over this one
function prepareImages($file,$url,$article)
{
$string = file_get_contents($file);
$json = json_decode($string,true);
$value = array();
//$array = $json['elements'];
//$imgArray = array();
/* if(['type'] == "image")
{
array_push($json['elements']['src'],$array);
} */
foreach($json['elements'] as $value)
{
if($value['type'] == "image")
{
$arr = explode('\\', $value['src']);
$count = count($arr);
$img = $arr[$count-1];
$src = $url.'res/'.$article.'/'.$img;
$value['src'] = $src;
//print_r($json);
}
//This prints all the values correctly
print_r($value);
}
$json = $value;
$string = json_encode($json);
file_put_contents($file,$string);
}
As per json_encode() documentation, that function escapes forward slashes, try doing this:
$value['src'] = str_replace('\\/', '/', $src)

How to reffer dynamically to a php ARRAY variable(s)?

Everybody knows that you can access a variable in PHP using this: ${'varName'}. But when you need to get/set a variable witch is part of an array, why doesn't it work ? Suppose we have this piece of code:
<?php
$myArray = array(...);
$myVarName = "myArray['my1']['my11']['my111']";
${$myVarName} = "new value";
?>
Shouldn't it work ?
I have tested it again and again - it is not working..
Is it there a way to do that?
I recommend you not to use dynamic variables like ${$var}.
What you want is modifying a multi-dimensional associative array according to a path of keys.
<?php
$myArray = array(...); // multi-dimensional array
$myVarPath = array('my1', 'my11', 'my111');
setValueFromPath($myArray, $myVarPath);
function getValueFromPath($arr, $path)
{
// todo: add checks on $path
$dest = $arr;
$finalKey = array_pop($path);
foreach ($path as $key) {
$dest = $dest[$key];
}
return $dest[$finalKey];
}
function setValueFromPath(&$arr, $path, $value)
{
// we need references as we will modify the first parameter
$dest = &$arr;
$finalKey = array_pop($path);
foreach ($path as $key) {
$dest = &$dest[$key];
}
$dest[$finalKey] = $value;
}
This is a procedural example to keep it simple. You may want to put your hierarchical array and this functions inside a class.
Shouldn't it work ?
No.
Everybody knows that you can access a variable in PHP using this: ${'varName'}.
Yes. Yet everybody knows that's lame.
How to refer dynamically to a php array variable(s)?
having array of ('my1','my11','my111') you can refer to any particular array member using merely a loop.
You could do something like this, but it would be a really bad idea. Sorry Col. ;)
<?php
$mA = array();
$mVN = "mA['m1']['m2']['m3']";
eval('$'. $mVN . ' = "new value";');
print_r($mA);
?>

Delete from json using php

my Current json code :
{"Results":[{"username":"test","password":"test"},{"username":"test","password":"test"},{"username":"google","password":"test"},{"username":"yahoo","password":"test"},{"username":"hotmail","password":"test"}]}
i want to remove this :
{"username":"google","password":"test"}
from the code using php.
i tried deleting by decoding json to array but cant get it done.
any solution ?
$json_obj = json_decode($json_string);
$unset_queue = array();
foreach ( $json_obj->Results as $i => $item )
{
if ($item->username == "google")
{
$unset_queue[] = $i;
}
}
foreach ( $unset_queue as $index )
{
unset($json_obj->Results[$index]);
}
// rebase the array
$json_obj->Results = array_values($json_obj->Results);
$new_json_string = json_encode($json_obj);
<?php
$JSON = '{"Results":['
. '{"username":"test","password":"test"},'
. '{"username":"test","password":"test"},'
. '{"username":"google","password":"test"},'
. '{"username":"yahoo","password":"test"},'
. '{"username":"hotmail","password":"test"}'
. ']}';
// use json_decode to parse the JSON data in to a PHP object
$jsonInPHP = json_decode($JSON);
// now iterate over the results and remove the one that's google
$results = count($jsonInPHP->Results);
for ($r = 0; $r < $results; $r++){
// look for the entry we are trying to find
if ($jsonInPHP->Results[$r]->username == 'google'
&& $jsonInPHP->Results[$r]->password == 'test'){
// remove the match
unset($jsonInPHP->Results[$r]);
// now we can either break out of the loop (only remove first match)
// or you can use subtract one from $r ($r--;) and keep going and
// find all possible matches--your decision.
break;
}
}
// now that we removed items the keys will be off. let's re-order the keys
// so they're back in-line
$jsonInPHP->Results = array_values($jsonInPHP->Results);
// dump the new JSON data, less google's entry
echo json_encode($jsonInPHP);
Would be how I approach it. I like to avoid foreach(...){} statements when I need to modify the array itself. The above code, by the way, leaves you with:
{
"Results":[
{"username":"test","password":"test"},
{"username":"test","password":"test"},
{"username":"yahoo","password":"test"},
{"username":"hotmail","password":"test"}
]
}
$json = '
{
"Results":[
{"username":"test","password":"test"},
{"username":"test","password":"test"},
{"username":"google","password":"test"},
{"username":"yahoo","password":"test"},
{"username":"hotmail","password":"test"}
]
}';
$arr = json_decode($json, true);
array_filter($arr, function($v) {
return !($v['username'] == 'google' && $v['password'] == 'test');
});
$json = json_encode($arr);
$input='{"Results":[{"username":"test","password":"test"},{"username":"test","password":"test"},{"username":"google","password":"test"},{"username":"yahoo","password":"test"},{"username":"hotmail","password":"test"}]}';
$json = json_decode($input,true);
$match = array('username'=>'google', 'password'=>'test');
unset($json['Results'][array_search($match,$json['Results'])]);
To do it without a foreach but assuming you know the exact values you want to remove
Old question, formatting your JSON differently would help a lot.
Each result entry should have a unique key to identify it.
This makes it easy when needing to remove or update that result.
No reason to iterate over entire JSON this way.
Code would look like this
<?php
$jsonString = '{"Results":{'
.'{"username1":{"username":"google","password":"test1"}}'
.'{"username2":{"username":"yahoo","password":"test2"}}'
.'{"username3":{"username":"msonline","password":"test3"}}'
. '}}';
$jsonInPHP = json_decode($jsonString);
$password = $jsonInPHP["username1"]["pasword"];//Returns test1
$username = $jsonInPHP["username1"]["username"];//Returns google
?>
$myArray=json_decode($theJSONstring);
unset($myArray['Results'][2]);

Categories