PHP - Deleting an element of a JSON array changes the array syntax - php

I can successfully delete elements of a JSON array with PHP, but I cannot understand why the JSON array changes syntax after deleting an element that's not the last one.
So, here's my User.json file:
[
{
"id": "kS79BhPx"
},
{
"id": "ycC7km7A"
},
{
"id": "hgF5D4es"
}
]
Here's my delete.php script:
$className = "Users";
// get the index
$index = (int)$_GET['index'];
//fetch data from json
$data = file_get_contents($className. '.json');
$data_array = json_decode($data, true);
// delete the row with the index
unset($data_array[$index]);
//encode back to json
$data = json_encode($data_array, JSON_PRETTY_PRINT);
file_put_contents($className. '.json', $data);
So, if I go to the following URL, just to test my php function:
https://example.com/delete.php?index=0
The script successfully deletes the first element of the JSON array, but then it changes into this:
{
"1": {
"id": "ycC7km7A"
},
"2": {
"id": "hgF5D4es"
}
}
Instead, if I set https://example.com/delete.php?index=2 - so I want to delete the last array's element - it saves it as follows:
[
{
"id": "kS79BhPx"
},
{
"id": "ycC7km7A"
}
]
This last result is what I need to achieve all the times I delete an element because I need the JSON array syntax to stay as [...], not as {...}.
What am I doing wrong in my PHP script?

Using unset() on an array (associative or not) in PHP will preserve the existing keys making the array associative. You need to reindex the array after using unset():
// delete the row with the index
unset($data_array[$index]);
$data_array = array_values($data_array);

Related

How to get a specific value from a json array out of a list of arrays

everyone, I was just trying to find out a way to get the value of a link from a JSON array , after I have searched the array with help of Id. I am using PHP's file_get_contents and the webpage from which information is to be taken looks like
[{
"id":"2972",
"name": "AbC",
"link":"any link",
"epg": "any link",
"dur": "disabled",
"language": "y",
"category": "TOP 100",
"logo": "any url here"
},
{
"id": "1858",
"name": "Efg",
"link": "url",
"epg": "url",
"dvr": "disabled",
"language": "E",
"category": "TOP 100",
"logo": "url"
}]
From here suppose I have been given an Id 1858 so I have to find a link from the array of Id having 1858
I am a beginner in PHP and was just fidgeting around with a piece of code and tried to get its solution and a big Thanks To You For Your Answer and valuable Time.
if you are using file_get_contents('php://input'); then you should try this to access json data
$json = file_get_contents('php://input'); //get json data in variable
$array = json_decode($json); //parse json data in php array
// assecc the array with use of foreach loop
foreach($array as $obj){
//access the json element here like $id = $obj->id; $url = $obj->link;
//if you want to check the id value in array you can compare value with if condition
$id = $obj->id;
// find link for specific id
if($id =='1858'){
$url = $obj->link;
echo $url; // do something with link
//you can use break; statement if you found your element and terminate the loop
}
}
You can use array_column, to map pairs of json keys/values:
<?php
$json ='
[
{
"id": 3,
"link": "http:\/\/example.com\/3"
},
{
"id": 5,
"link": "http:\/\/example.com\/5"
}
]';
$data = json_decode($json, true);
if($data !== null) {
echo array_column($data, 'link', 'id')[5] ?? null;
}
Output:
http://example.com/5
To understand this we can see the result of array_column.
var_export(array_column($data, 'link', 'id'));
Output:
array (
3 => 'http://example.com/3',
5 => 'http://example.com/5',
)
So with the above code, we are checking for and outputting the associated index of 5 (the original id).

Get JSON Data From .json (php)

i'm trying to get the fields "name, price, image and rarity" to show in a php file, anyone can help me? Thanks ;D
{
"status": 300,
"data": {
"date": "2019-09-16T00:00:00.000Z",
"featured": [
{
"name": "Flying Saucer",
"price": "1,200",
"images": {
"icon": icon.png",
},
"rarity": "epic",
},
I'm using this that a friend told me, but i cant put that to work :c
<?php
$response = json_decode(file_get_contents('lista.json'), true);
foreach ($response as $val) {
$item = $val['name'];
echo "<b>$item</b>";
}
?>
I'm not quite sure what you are trying to achieve. You can just access the contents via the $response array like this:
echo $response['status']; // would output 300
You can use foreach to iterate through the array. For example: If you want to output the name of every element of the array you can use:
foreach ($response['data'] as $val) { // loop through every element of the data-array (if this makes sense depends on the structure of the json file, cant tell because it's not complete)
echo $val['featured']['name'];
}
You gotta get the index in $val['data']['featured']['name'] to retrieve the name index.
When you defined the second parameter of json_decode, you said that you want your json to be parsed to an array. The brackets in the original json identify when a new index of your parsed array will begin.
I suggest you to read about json_decode and json in general:
JSON: https://www.json.org/
json_decode function: https://www.php.net/manual/en/function.json-decode.php

JSON object with array header

this question comes from the posting I found here:
DataTables Multiple Tables from Multiple JSON Arrays
I'd like to know the simplest and best way to generate the JSON below. I can see the pattern is 'JSON object -> Array Header -> Array -> JSON object' but I do not know how to do this in PHP, from a mySQLi query result. I imagine having a mySQL table with a 'policies' and 'services' column so the query might look something like:
Select name, id, score, type from myTable where type = 'policies' and
type = 'services'
And the result would come back something like:
name id score type
A 1 0 policies
B 2 0 services
But then how would I take that query and generate this JSON in php?
{
"Policies": [
{
"name": "A",
"id": "1",
"score": "0"
}
],
"Services": [
{
"name": "B",
"id": "2",
"score": "0"
}
]
}
Thanks for your help!
Start by creating the new empty array.
Then, iterate through the result and add it in the correct sub-array:
$new = [];
foreach ($result as $item) {
// Uppercase the first character
$type = ucfirst($item['type']);
if (!isset($new[$type])) {
// This type doesn't exist in the new array yet, let's create it.
$new[$type] = [];
}
// Add the item
$new[$type][] = $item;
}
// Output it as json
echo json_encode($new, JSON_PRETTY_PRINT);
The above code will also work if new types are added to the database.
PS. The JSON_PRETTY_PRINT argument is just to make the json string a bit more readable while developing. When everything looks good, you can remove it.

Multidimensional Array Information Grabbing

I have an array that looks as such:
{
"stocks": {
"0": {
"name": "Stock Exchange",
"current_price": 12843.973,
"available_shares": 0,
},
"1": {
"acronym": "TSBC",
"current_price": 503.106,
"available_shares": 171252632,
"benefit": {
"requirement": 4000000,
"description": "Entitled to receive occasional dividends"
}
},
and from number 1, I need to grab current_price. I have a foreach that grabs it from both, but I'm not sure how to only grab the info from number 1, being the second block of information - TSBC. Any ideas?
As you added the json tag to your question, I must note that you have presented an invalid json content. There is unexpected comma right after the number 0 within the first "stocks" object "available_shares": 0,.
So let's remove that comma and if we talk about "multidimensional array" let's decode our json string into associative array with json_decode function in such way:
// $str - is some part of your json string
$str = '{
"stocks": {
"0": {
"name": "Stock Exchange",
"current_price": 12843.973,
"available_shares": 0
},
"1": {
"acronym": "TSBC",
"current_price": 503.106,
"available_shares": 171252632,
"benefit": {
"requirement": 4000000,
"description": "Entitled to receive occasional dividends"
}
}}}';
$arr = json_decode($str, true);
// now we are able to get 'current_price' from the second element of array
var_dump($arr['stocks'][1]['current_price']);
// the output:
float 503.106

json_encode, json_decode, array?

I'm trying to get into just data from
{
"data": [{
"media_count": 3045,
"name": "snow",
},
{
"media_count": 79,
"name": "snowman",
},
{
"media_count": 40,
"name": "snowday",
},
{
"media_count": 29,
"name": "snowy",
}]
}
I've been trying, using:
$obj = json_decode($res[0], true);
echo $obj['data']; //this returns an array
I also tried this:
$obj = json_encode($res[0], true);
echo $obj; // this returns json, but not inside `data`
"data": [{
"media_count":54373,
"name":"test"
}]
I just want to get inside data. How would I do so?
Thanks in advance!
UPDATE: Sorry to mention, I would like this in json format please
eventually, I would like to only see
{
"media_count":54373,
"name":"test"
}
Something like thiat
Use json_encode() to get what you want:
$obj = json_decode($res[0], true);
echo json_encode($obj['data']);
In your first example, $obj['data'] returns an array because that's how the JSON is set up. According to the JSON, data is a collection of elements.
To access within the array, you can do this:
foreach($obj['data'] as $object) {
print_r($object);
}
You can also index into it as you want:
print_r($obj['data'][0]);
EDIT
If I'm getting you correct, you want to convert the first JSON to this:
"data": [{
"media_count":54373,
"name":"test"
}]
If so, that is not possible since the second fragment is not valid JSON. (use http://jsonlint.com)
firstly access the data item of the json array;
$obj1=$obj[item];
$sizeobj=sizeof($obj1);
for($i=0;$i<$sizeobj;$i++)
{
// your code to access the data items
// for eg $obj[item][$i][media_count}
}

Categories