Just decode your json string and then use array push
$tempArray = json_decode($jsonstring, true);
array_push($tempArray, $your_data);
For your case
$str = '{
"players":[
{
"name":"Moldova",
"image":"/Images/Moldova.jpg",
"roll_over_image":"tank.jpg"
},
{
"name":"Georgia",
"image":"/Images/georgia.gif",
"roll_over_image":"tank.jpg"
} ]}';
$arr = json_decode($str, true);
$arrne['name'] = "dsds";
array_push( $arr['players'], $arrne );
print_r($arr);
Just check value of print_r($arr); I hope this is what you want. :)
Answer from chandresh_cool on Stack OverflowJust decode your json string and then use array push
$tempArray = json_decode($jsonstring, true);
array_push($tempArray, $your_data);
For your case
$str = '{
"players":[
{
"name":"Moldova",
"image":"/Images/Moldova.jpg",
"roll_over_image":"tank.jpg"
},
{
"name":"Georgia",
"image":"/Images/georgia.gif",
"roll_over_image":"tank.jpg"
} ]}';
$arr = json_decode($str, true);
$arrne['name'] = "dsds";
array_push( $arr['players'], $arrne );
print_r($arr);
Just check value of print_r($arr); I hope this is what you want. :)
Adding another player
$tempArray = json_decode($inp, true);
array_push($tempArray['players'], array('name' => $data['username'], 'image' => $data['userimage'], 'roll_over_image' => 'tank.jpg'));
Updating matches
first match array
$tempArray['games'][0]['matches'];
second match array
$tempArray['games'][1]['matches'];
are now simple two dimensional arrays with keys player1id, player2id and winner - it should be easy to update these.
After that you can encode the $tempArray back to json.
$data = json_decode($file, true);
//When TRUE, returned objects will be converted into associative arrays.
unset($file);
$newImage = array('image' => $link, 'folder' => $category);
//$newImage['image'] = $link;
//$newImage['folder'] = $category;
$result = array_merge($data, $newImage);
//don't need to cast
Reference PHP json_decode Manual
Edit The following code works (tested)
function addToJsonImageList($link, $category) {
$file = file_get_contents('./images_list.json', true);
$data = json_decode($file,true);
unset($file);
//you need to add new data as next index of data.
$data[] = array('image' => $link, 'folder' => $category);
$result=json_encode($data);
file_put_contents('./images_list.json', $result);
unset($result);
}
Edit 2 added lot of error reporting and debugging. Please let me know the output of the following. The code below is not tested (just typed in here).please fix if you find any syntax error. it is late here and can only check tomorrow my time, but can reply.
<?php
//display all errors and warnings
error_reporting(-1);
addToJsonImageList('test link', 'test category');
function addToJsonImageList($link, $category) {
$file = file_get_contents('./images_list.json', true);
if ($file===false)die('unable to read file');
$data = json_decode($file,true);
if ($data ===NULL)die('Unable to decode');
unset($file);
echo "data before\n";
var_dump ($data);
//you need to add new data as next index of data.
$data[] = array('image' => $link, 'folder' => $category);
echo "data after\n";
var_dump ($data);
$result=json_encode($data);
if (file_put_contents('./images_list.json', $result) === false){
die('unable to write file');
}
unset($result);
}
?>
Lets say you have this .json file named (playerJson)
{
"Players":
[
{"Name":"Arun","Arm":"Gun","num":"1"},
{"Name":"sssv","Arm":"Arc","num":"2"},
{"Name":"Surya","Arm":"Bomb","num":"3"},
{"Name":"sssv","Arm":"Fire","num":"4"}
]
}
Now what we have to do in php (myPhpFile.php) is : (I suppose you are loading your data from a form)
<?php
$json = file_get_contents('playerJson.json');
$json_data = json_decode($json,true);
$newar = array(
'Name'=>$_POST['nameField'] ,
'Arm' =>$_POST['armField'],
'Num' =>$_POST['numField']
);
//saving data in Players object...
array_push($json_data['Players'], $newar);
$json = json_encode($json_data);
file_put_contents('playerJson.json', $json);
?>
That's all ! You have a new line in your "Players" Object. But if you want to add a new object, avoid the [Players] after $json_data in the array_push function.
Easy peasy lemon squeezy: http://www.php.net/manual/en/function.json-encode.php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
There's a post by andyrusterholz at g-m-a-i-l dot c-o-m on the aforementioned page that can also handle complex nested arrays (if that's your thing).
Use PHP's native json_encode, like this:
<?php
$arr = array(
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
)
);
echo json_encode($arr);
?>
Update: To answer your question in the comment. You do it like this:
$named_array = array(
"nome_array" => array(
array(
"foo" => "bar"
),
array(
"foo" => "baz"
)
)
);
echo json_encode($named_array);
You want to json_encode($json, JSON_FORCE_OBJECT).
The JSON_FORCE_OBJECT flag, as the name implies, forces the json output to be an object, even when it otherwise would normally be represented as an array.
You can also eliminate the use of array_push for some slightly cleaner code:
$json[] = ['ip' => $ip, 'port' => $port];
just use only
$response=array();
$response["0"]=array("ip" => "192.168.0.1",
"port" => "2016");
$json=json_encode($response,JSON_FORCE_OBJECT);
You're treating this like string manipulation, which is the dead wrong way to go about it. You need to combine the two structures while they're objects, before you re-encode them to JSON.
These three lines...
$data = json_encode($data);
$oldData = json_encode($oldData);
file_put_contents('base.json', '['.$data.','.$oldData.']');
Should be rewritten as...
// Create a new array with the new data, and the first element from the old data
$newData = array($data, $oldData[0]);
$newData = json_encode($newData);
file_put_contents('base.json', $newData);
Add the new data to the array with:
$oldData[] = $data;
Then write it back to the file:
file_put_contents('base.json', json_encode($oldData));
The idea is to need to convert the JSON to array using json_decode, manipulate the fields, and encode it back in JSON format.
Try this:
$decoded_json = json_decode($json1, true);
$decoded_json[0]['fields'] = json_decode($json2, true);
$finalJSON = json_encode($decoded_json, JSON_PRETTY_PRINT);
Thats not json. its an array of objects
You can achieve what you want simply with
$json1[0]->fields = $json2;