indexing JSON in php after removing item - php

How can I re-index a JSON after using unset($json -> nodes[$data_deleteNode]) to remove an entry? The common method array_values($json), which usally close the gaps doesn´t work. I understand the error message but do not have an idea to solve it.
array_values() expects parameter 1 to be array, object given
There is a similar thread which refers to the solutions I tried - PHP json_encode as object after PHP array unset() the only difference is the JSON.
If I do not perform any sorting, unset() adds an index which cause my JSON to be not readable for other scripts.
The affected PHP:
<?php
header("Access-Control-Allow-Origin: *");
$data_deleteNode = ($_POST['id']);
$json = file_get_contents("data2.json");
$json = json_decode($json);
//$data_deleteNode = json_decode($data_deleteNode);
//array_splice($json, 3, 1);
printf("%s\n", json_encode($json));
unset($json -> nodes[$data_deleteNode]);
printf("%s\n", json_encode($json));
$json = array_values($json);
$json = json_encode($json);
file_put_contents("data2.json", $json)
?>
UPDATE: modified playground which shows the error https://3v4l.org/XPbuo#v730

$json = file_get_contents("data2.json");
$data = json_decode($json);
unset($data->nodes[$data_deleteNode]);
$data->nodes = array_values($data->nodes);
$json = json_encode($data);
file_put_contents("data2.json", $json)
$data->nodes is the array you're modifying and that you need to reset. You do that with:
$data->nodes = array_values($data->nodes);
Note also that I renamed your variables so $json refers to JSON encoded text, and $data refers to decoded arrays/objects.

Related

Decode php://input json

I have this text from file_get_contents('php://input'):
[{"email":"text#examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw#ismon1.sendgrid.net>","timestamp":16813363}]
I need to get single element like email or event, but haven't been able to get json_decode and others to work.
$obj = json_decode(file_get_contents('php://input'));
How can I reference a single element in the json data?
You have an array, so, you need to get the first element:
$json = '[{"email":"text#examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw#ismon1.sendgrid.net>","timestamp":16813363}]';
$obj = json_decode($json);
echo $obj[0]->email; //output text#examlple.com
Here you go, here's a fully working answer:
<?php
$str = '[{"email":"text#examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw#ismon1.sendgrid.net>","timestamp":16813363}]';
$obj = json_decode($str);
echo $obj[0]->email;

PHP get curl array results from inside a key value

I'm trying to get the access_token value from a curl response. The key value which is [0] renders out like so, {"access_token":"430f8a7d4f721a9e51e3558689ff28ec592923d2","expires_in":3600,"token_type":"Bearer","scope":null}.
However, I just need the value nested inside of access_token, which is 430f8a7d4f721a9e51e3558689ff28ec592923d2.
The output is rendered using this:
$cmd="curl -u testuser:123456 http://localhost/oauth2/server/token.php -d 'grant_type=client_credentials'";
exec($cmd,$result);
echo '<pre>'; print_r($result[0]); echo '</pre>';
How might go about doing this?
Btw, none of this is sensitive data. I'm just experimenting with oauth2.
Use the json_decode function on the results.
<?php
$json = '{"access_token":"430f8a7d4f721a9e51e3558689ff28ec592923d2","expires_in":3600,"token_type":"Bearer","scope":null}';
// Decode the JSON into an object
$decodedJson = json_decode($json);
$accessToken = $decodedJson->access_token;
var_dump($decodedJson,$accessToken);
// Decode the JSON into an array (note the true on the decode)
$decodedJson = json_decode($json,true);
$accessToken = $decodedJson['access_token'];
var_dump($decodedJson,$accessToken);
Encoding the json result, finds the subset.
$json = $result[0];
$json = json_decode($json, true);
echo $json['access_token'];

How to take out int value from JSON object?

I'm working with Laravel 5 right now and I have the following problem. I've got response from DB query:
[{"id":1}]
and I want to take out 1 as int or string. Any ideas?
I've tried to solve this like follows:
$json = (DB query);
$data = json_decode($json);
$final = $data[0]->id;
and response is :
json_decode() expects parameter 1 to be string, array given
This is all you need.
$response = json_decode($response); // Decode the JSON
$string = $response[0]->id; // Save the value of id var
As you say, the string you have is in JSON format, so you need to use json_decode to access it in PHP.
The square brackets refer to an array, and the braces refer to an object within that array, so what you're looking for is the id value of the first element (i.e. element 0) in the array.
<?php
$json = '[{"id":1}]';
$data = json_decode($json);
echo $data[0]->id;
// 1
Try this
$json_array = '[{"id":1}]';
$data = json_decode($json_array);
print_r($data); // To display the result array
You just need to decode it, if I'm not misunderstanding your questions.
$json = '[{"id":1}]';
$decodedObject = json_decode($json);
Then you can loop through the aray and do something with your data:
foreach($decodedObject as $key => $value) {
$id = $value->id;
}
If you're using Laravel, though, why not use Eloquent models?

PHP json_Encode an array of json_encode-ed arrays

Im not sure what is happening, but if i do
json_encode()
On a single array, i get valid json, but if i do something like
$ar['key'] = "name";
$array[] = json_encode($ar);
$json = json_encode($array);
It will return invalid json like so:
["{"key":"name"}"]
The expected outcome is
[{"key":"name"}]
I have searched for hours trying to find what is going on.
Due to lack of desired outcome, I can only assume you are trying to get a multidimensional array.
The correct way to achieve this would be to build an array of arrays, and then json_encode the parent array.
$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
$json = json_encode($data);
Following this code, $json will have the following value
{"fruits":["apple","banana","cherry"],"animals":["dog","elephant"]}
It could then be parsed properly by javascript using jQuery.parseJSON()
Just json_encode the entire array.
$ar['key'] = "name";
$json = json_encode($ar);
json_encode returns a string, and json encoding a string will return a string.
Also it's json_encode, not $json_encode

PHP get variable from json results

Using PHP I have a json result of
{"text_block":[{"text":"XYZ","left":0,"top":0,"width":10,"height":12}]}
I can get this printed by the below code:
$json= file_get_contents('https://api.url');
$result = json_decode($json, true); //this returns an array
$result = json_decode($json);
$data = get_object_vars(json_decode($json));
$data = array_slice( $data, 0, 10 ); // now you can array functions
echo json_encode( $data );
but need to put the text "XYZ" into a variable for further use in PHP script. How can I do this, I've check various sources but don't seem to be getting anywhere! Thanks
$res = json_decode($data,true);
$my_text = $res['text_block'][0]['text'];
now you can use my_text as a variable
It looks like the value "XYZ" would be in
$data["text_block"][0]["text"]
Temporarily change the last line to var_dump($data) so you can get familiar with the php array structure.

Categories