I am trying to sent response in that form
{"files":[{"webViewLink":""},{"webViewLink":""}]}
But I'm getting response like that
{"files":[{"webViewLink":"""}]}{"files":[{"webViewLink":"""}]}
Here is my PHP code:
<?php
$idtemp = extractfiles($fol_id, $email);
foreach ($idtemp['items'] as $val) {
$id = $val['id'];
$val = array(
"webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"'
);
$enc = json_encode($val);
$val = '{"files":['.$enc.']}';
echo($val);
Please help me to fix code i need response in that way
{"files":[{"webViewLink":""},{"webViewLink":""}]}
You should no do $val = '{"files":['.$enc.']}';
Use json_encode to make json, don't do it manual
Create an object with desired keys outside the loop
Push anything to the desired array
Convert to json
<?php
$idtemp = extractfiles($fol_id, $email);
$json = (object) [
"files" => []
];
foreach ($idtemp['items'] as $val) {
$json->files[] = (object) [
"webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"'
];
}
$json = json_encode($json);
echo($json);
If I use some dummy values to create an example, the output is:
{
"files": [
{
"webViewLink": "https://drive.google.com/file/d/1/view?usp=drivesdk\""
},
{
"webViewLink": "https://drive.google.com/file/d/2/view?usp=drivesdk\""
},
{
"webViewLink": "https://drive.google.com/file/d/3/view?usp=drivesdk\""
}
]
}
As you can test in this online demo
Related
I am having trouble getting the name of a dynamic key from a JSON string.
I am using PHP
This is a sample of the JSON
{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}
I am using foreach to go trough the json key and get the values
foreach ($json as $obj) {
$search_term = $obj->_text;
$msg_id = $obj->msg_id;
}
But I am not sure how to get the value of the "dynamic_key" which changes every time, and because of that I also cannot get the values of "confidence and value" keys.
Any ideas on how to approach this?
Followed #Dimi, solution. This is what I ended up with
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "Entity: $key";
foreach ($data['entities'] as $keys){
$conf = $keys[0]['confidence'];
$answer = $keys[0]['value'];
echo "conf: $conf, answ: $answer";
}
}
Can you provide a couple more examples?
Or try this code and let us know if it breaks
<?php
$json='{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}';
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "VALUE IS $key\n values are ";
var_dump($val);
}
Using the data you've shown, there doesn't seem to be an array for the starting JSON.
But with that data the following will use foreach to both fetch the key and the data and then another sub-loop to fetch the confidencevalue...
$search_term = $json->_text;
$msg_id = $json->msg_id;
foreach ( $json->entities as $key => $entities ) {
echo $key.PHP_EOL;
foreach ( $entities as $entity) {
echo $entity->confidence.PHP_EOL;
}
}
If you decode the JSON as an array and if the dynamic key is the only key under entities, then:
$array = json_decode($json, true);
$dynamic = current($array['entities']);
$confidence = $dynamic['confidence'];
$value = $dynamic['value'];
Or shorter:
$confidence = current($array['entities'])['confidence'];
You can probably use reset, current and maybe array_pop etc.
I want to find index of key from json array similar to this question Get index of a key in json
but i need the solution using php.
here is my json (partial data)
{
"currentOver":{
"events":[]
},
"matchString":"",
"currentPlayer":5,
"previousOvers":[],
"innings":[],
"scorecards":[
{
"batting":{
"players":[
{"id":16447,"name":"Rahul Roy"},
{"id":12633,"name":"Sijal Thomas"},
{"id":16446,"name":"Mohammed Reza"},
{"id":16509,"name":"Asif Khan"},
{"id":12633,"name":"Koyel Dijesh"},
{"id":16468,"name":"Shahrook"},
{"id":64691,"name":"Shafiq"},
{"id":6518,"name":"Ubaidulah"}
]
}
}
]
}
and php
foreach ($read_json->scorecards->batting->players as $batsmen => $val) {
if($val == 5) { // if batsman index is 5 then display his name
$name = $batsmen->name;
echo "<div>$name</div>\n";
}
}
Please help me to solve this issue.Thanks in advance.
I think this would suffice your requirement
http://codepad.org/XQDCKAsB
Find the code sample below as well.
$json = '{"currentOver":{"events": []},"matchString":"","currentPlayer":5,"previousOvers":[],"innings":[],"scorecards":[{"batting":{"players":[{"id":16447,"name":"Rahul Roy"},{"id":12633,"name":"Sijal Thomas"},{"id":16446,"name":"Mohammed Reza"},{"id":16509,"name":"Asif Khan"},{"id":12633,"name":"Koyel Dijesh"},{"id":16468,"name":"Shahrook"},{"id":64691,"name":"Shafiq"},{"id":6518,"name":"Ubaidulah"}]}}]}';
$arr = json_decode($json);
echo '<pre>';
$currentPlayer = $arr->currentPlayer;
echo $arr->scorecards[0]->batting->players[$currentPlayer-1]->name;
Try this code.
$info = json_decode('json string');
$currentPlayer = $info->currentPlayer;
$batsman = $info->scorecards[0]->batting->players[$currentPlayer];
echo "<div>{$batsman->name}</div>\n";
Also, note that arrays in PHP are zero-based. If currentPlayer index in json data is based on 1 (rare case, but it exists sometimes) you will ned to use
$batsman = $info->scorecards[0]->batting->players[$currentPlayer - 1];
to get right item from array.
If you just want to fix your foreach
$read_json->scorecards->batting should become $read_json->scorecards[0]->batting
if($val == 5) should become if($batsmen == 5)
$name = $batsmen->name; should become $name = $val->name;
You need to use json_decode and array_keys for the array keys from the json.
$json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
$result = json_decode ($json, true);
$keys = array_keys($result);
print_r($keys); //Array ( [0] => key1 [1] => key2 [2] => key3 )
In Php, You can use the code below, if you wan to fix it using foreach loop
foreach($json->entries as $row)
{
foreach($row as $key => $val)
{
echo $key . ': ' . $val;
echo '<br>';
}
}
please have a look following code
$json=json_decode($data)->scorecards[0]->batting->players;
foreach ($json as $key => $value) {
if($key==5){
echo $value->name ;
}
}
You can do it using converting JSON string to Array
$json_str = '{
"currentOver":{
"events":[]
},
"matchString":"",
"currentPlayer":5,
"previousOvers":[],
"innings":[],
"scorecards":[
{
"batting":{
"players":[
{"id":16447,"name":"Rahul Roy"},
{"id":12633,"name":"Sijal Thomas"},
{"id":16446,"name":"Mohammed Reza"},
{"id":16509,"name":"Asif Khan"},
{"id":12633,"name":"Koyel Dijesh"},
{"id":16468,"name":"Shahrook"},
{"id":64691,"name":"Shafiq"},
{"id":6518,"name":"Ubaidulah"}
]
}
}
]
}';
Decode your JSON string using "json_decode" and you get array
$json_decode_str = json_decode($json_str, true);
Now using foreach you can do anything
if($json_decode_str['scorecards']){
foreach($json_decode_str['scorecards'] as $scorecard){
$player_index = 1;
if($scorecard['batting']['players']){
foreach($scorecard['batting']['players'] as $player){
if($player_index == 5){
echo $player['name'];
}
$player_index++;
}
}
}
}
Maybe this one help you :)
I'm trying to convert my array to JSON.
My JSON is stored in the database and will later be decoded for permission checking.
Example,
How I want it to be stored in the database:
{ "admin": 1,
"create_posts": 1,
"edit_posts": 1,
"delete_posts": 1 }
How it is being stored now:
{"0":"\"admin\": 1",
"1":"\"create_posts\": 1",
"2":"\"edit_posts\": 1",
"3":"\"delete_posts\": 1"}
My code:
$check_list = $_POST['check_list'];
$list = array();
foreach($check_list as $key) {
$key = '"' . $key .= '": 1';
array_push($list, $key);
}
$json = json_encode($list, JSON_FORCE_OBJECT);
How would I make it so that it stores in the database like I want it to be?
I'm quite new to this, so any hints instead of direct answers is also much appreciated!
UPDATE:
JSON decode and validation:
$permis = json_decode($permissions->permissions, true);
echo ($permis['admin'] == true) ? 'allowed' : 'disallowed';
$arr = [ 'a', 'b', 'c' ];
echo json_encode(
array_combine(
$arr,
array_fill(0, count($arr), 1)
),
JSON_PRETTY_PRINT
);
Output:
{
"a": 1,
"b": 1,
"c": 1
}
http://us3.php.net/manual/en/function.array-combine.php
http://us3.php.net/manual/en/function.array-fill.php
I'm assuming the incoming data looks like this.
$incoming_data = "admin=1&create_posts=1&edit_posts=1&delete_posts=1";
$pairs = parse_str($incoming_data);
so we take the incoming pairs and use the $key as the array index so you don't get the extra array element index.
$permissions = array();
foreach($pairs as $key => $value){
$permissions[$key] = $value;
}
then we encode the new array to get the JSON you're looking for.
print json_encode($permissions);
will print out JSON like this:
{
"admin":"1",
"create_posts":"1",
"edit_posts":"1",
"delete_posts":"1"
}
The main thing to change in your code is this.
foreach($check_list as $key) {
$list[$key] = 1;
}
I am new to PHP and I am working on wordpress JSON api. I want to remove Key:value pair inside a JSON array. Please help
{
"status":"ok",
"post":{
"id":23,
"type":"post",
"slug":"head-ache",
"url":"http:\/\/xyz.com\/maruthuvam\/2015\/06\/17\/head-ache\/",
"status":"publish",
"title":"Head Ache",
"title_plain":"Head Ache",
"content":"<p>content<\/p>\n<p> <\/p>\n",
"excerpt":"<p>content <\/p>\n",
"date":"2015-06-17 19:35:47",
"modified":"2015-06-18 07:35:39",
"categories":[
{
"id":1,
"slug":"head",
"title":"Head",
"description":"http:\/\/xyz.com\/maruthuvam\/wp-content\/uploads\/2015\/06\/universa_-male_head_3d_model_01.jpg",
"parent":0,
"post_count":3
}
],
"tags":[
],
"author":{
"id":1,
"slug":"admin",
"name":"admin",
"first_name":"",
"last_name":"",
"nickname":"admin",
"url":"",
"description":""
},
"comments":[
],
"attachments":[
],
"comment_count":0,
"comment_status":"closed",
"custom_fields":{
}
},
"next_url":"http:\/\/xyz.com\/maruthuvam\/2015\/06\/17\/head- lice\/"
}
For example I want to remove "slug":"head-ache" from "post" and "post_count":0, from "categories" and "next-url". Please help.
UPDATE::
I have added the code in core.php and its not working. Can you please help me out.
public function get_post() {
global $json_api, $post;
$post = $json_api->introspector->get_current_post();
if ($post) {
$previous = get_adjacent_post(false, '', true);
$next = get_adjacent_post(false, '', false);
$response = array(
'post' => new JSON_API_Post($post)
);
if ($previous) {
$response['previous_url'] = get_permalink($previous->ID);
}
if ($next) {
$response['next_url'] = get_permalink($next->ID);
}
// parsing json
$arr = decode_json($response);
// removing the value
unset($arr['post']['slug']);
// and back to json
$response = json_encode($arr);
return $response;
} else {
$json_api->error("Not found.");
}
}
Just convert it to a PHP Array:
$jsonArray = json_decode($jsonString);
Remove the Keys
unset($jsonArray['post']['slug']);
And convert back:
$newJson = json_encode($jsonArray);
You need to parse it to ordinary array, then remove what you want and encode it back to json:
// parsing json
$arr = decode_json($yourJson);
// removing the value
unset($arr['post']['slug']);
// and back to json
$editedJson = json_encode($arr);
$a= json_decode($data,true);
unset($a['post']['slug']);
unset($a['next_url']);
$count= count($a['post']['categories']);
for($i=0 ; $i < $count ; $i++){
unset($a['post']['categories'][$i]['post_count']);
}
echo json_encode($a);
I've got this PHP code
<?php
$json = file_get_contents('comments.json');
$decode = json_decode($json);
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
foreach($decode->comments as $key)
{
var_dump(array(
$key->name,
$key->email,
$key->comment
));
}
$decode->comments = array(array('name'=>$name, 'email'=>$email, 'comment'=>$comment));
$encode = json_encode($decode,JSON_FORCE_OBJECT);
file_put_contents('comments.json',$encode);
?>
It kind of works, it sets the current stuff in the JSON file to what its told to in this piece of PHP code. Instead of this, I want the PHP code to add on to the JSON that is already existing.
This is the JSON file.
{
"comments": {
"0": {
"name": "123",
"email": "123",
"comment": "123"
}
}
}
Pass a boolean true so you get an associative array instead of an object-based decode:
$json = file_get_contents('comments.json', true);
Change all of your OOP references to associative array style:
foreach($decode['comments'] as $key)
{
var_dump($key); // Declaring a whole new array isn't really needed here
}
Append to the decoded JSON array using the [] syntax:
$decode['comments'][] = array(
'name' => $name,
'email' => $email,
'comment' => $comment,
);
Re-encode and return the resulting JSON:
$encode = json_encode($decode, JSON_FORCE_OBJECT);
file_put_contents('comments.json',$encode);