how to add array without creating a id number? - php

$url = file_get_contents("http://api.themoviedb.org/3/movie/000008?append_to_response=credits,images&api_key=###");
$json = json_decode($url, true)
$inp = file_get_contents('test3.json');
$tempArray = json_decode($inp,true);
$test = array($title=>$json);
array_push($tempArray, $test);
$jsonData = json_encode($tempArray,JSON_FORCE_OBJECT);
file_put_contents('test3.json', $jsonData);
when i add new array it creates a id number like this - >
"Ariel": {
"adult": false,
"backdrop_path": "\/z2QUexmccqrvw1kDMw3R8TxAh5E.jpg",
"belongs_to_collection": {
"id": 8384,
"name": "Proletariat Collection",
"poster_path": null,
"backdrop_path": "\/ibLeWo3X3dVo4rxvn4m3y90ms1I.jpg"
},
"0": {
"Varjoja paratiisissa": {
"adult": false,
"backdrop_path": "\/6YjUX87VtIEuDzanBE6obVxE9V3.jpg",
"belongs_to_collection": {
"id": 8384,
"name": "Proletariat Collection",
"poster_path": null,
"backdrop_path": "\/ibLeWo3X3dVo4rxvn4m3y90ms1I.jpg"
},
"1": {
"Life in Loops (A Megacities RMX)": {
"adult": false,
"backdrop_path": "\/udvB86uyzJ6P9vmB83WfrCbnmnI.jpg",
"belongs_to_collection": null,
"budget": 42000,
"genres": {
"0": {
"id": 99,
"name": "Documentary"
}
}
first one is ok but then it adds new id number befire movie title .i Dont want to add id number. please can anyone help me how add new array without creating id number?

sort() can change the array indices into numbers.
JSON_FORCE_OBJECT may not need.
So:
array_push($tempArray, $test);
sort($tempArray);
$jsonData = json_encode($tempArray);

Your code seems incomplete but try to replace
$test = array($title=>$json);
array_push($tempArray, $test);
by
$tempArray[$title] = $json;

If all the entries in the test3.json come from the same API (so have the same shape), just push the next entry in the array without setting a key manually. In the long run you'll get an array of all movies that is easy to traverse.
$newMovie = json_decode($url,true);
$allMovies = json_decode(file_get_contents('test3.json'),true);
$allMovies[] = $newMovie;
$jsonData = json_encode($allMovies,JSON_FORCE_OBJECT);
file_put_contents('test3.json',$jsonData);

Related

How can I define an array without a key within another array?

The title sounds a bit confusing, although I'm sure there's a simple solution. I'm using json_encode and am working on a web API. The web API will echo an array that is json_encoded. I want it to look like this:
{
{
"id": "test",
"reason": "test reason"
},
{
{
"id": "test2",
"reason": "test reason2"
}
}
I've tried this:
$array = array();
$array[""] = array();
$array[""]["id"] = "test";
$array[""]["reason"] = "test reason";
$array[""] = array();
$array[""]["id"] = "test";
$array[""]["reason"] = "test reason";
This still has a key though ("") which is annoying. I don't want a key. How can I fix this? Thanks! :)
I think this is more in line with your original code, you nearly had it nailed
<?php
$array = array();
// create 1st detail entry
$arrayDetail = array();
$arrayDetail["id"] = "test";
$arrayDetail["reason"] = "test reason";
$array[] = $arrayDetail; // add detail to array
// create 2nd detail entry
$arrayDetail = array();
$arrayDetail["id"] = "test";
$arrayDetail["reason"] = "test reason";
$array[] = $arrayDetail; // add detail to array
// show the output
var_dump(json_encode($array, JSON_PRETTY_PRINT));
{
{
"id": "test",
"reason": "test reason"
},
{
{
"id": "test2",
"reason": "test reason2"
}
}
This cannot be done for good reason : in javascript, the curly brackets indicate an object. Within an object, each property must have a key. The brackets on the other end indicate a numerically-indexed Array.
The Array type in php may be confusing because it's an all-in-one array, you can mix and match the keys as you see fit.
So this, instead, is valid JSON and might be what you really need (if you don't care about the keys, you'll need to loop over the values):
[
{
"id": "test",
"reason": "test reason"
},
{
{
"id": "test2",
"reason": "test reason2"
}
]
EDIT
You may create such an array in php through json_encode() like this :
$array = [["id"=> "test","reason"=> "test reason"],["id"=> "test","reason"=> "test reason"]];
echo json_encode($array);
You may get such format as below with array_push method,
$array = array();
array_push($array, array('id' => 'test', 'reason' => 'test reason' ) );
echo json_encode($array);
The resut will be a valid json format as
[{"id":"test","reason":"test reason"}]

PHP - object array into json

array of $setting['accountType'] :
$setting['accountType']['all'] = 'ALL';
$setting['accountType']['A1'] = 'VIP1';
$setting['accountType']['A2'] = 'VIP2';
PHP code to generate the object:
$object = new stdClass();
$myArray = array();
foreach ($setting['accountType'] as $key => $val)
{
$object->id = $key;
$object->desc = $val;
$myArray[] = $object;
}
$accountType = $myArray;
PHP code to format object into json:
json_encode(['accountType'=> [(object)$accountType]));
However, i get the output as below :
"accountType": [{
"0": {
"id": "A2",
"desc": "VIP"
},
"1": {
"id": "A2",
"desc": "VIP"
},
"2": {
"id": "A2",
"desc": "VIP"
}
}]
Problem 1: why $accountType only keep the last object when I loop through?
Problem 2: without the array key of $accountType [solved by using array_values($accountType)]
This is something that I am trying to achieve:
"accountType": [{
"id": "all",
"desc": "All "
}, {
"id": "A1",
"desc": "Normal"
}, {
"id": "A2",
"desc": "VIP"
}]
How to get the output as above?
You should use
json_encode(['accountType'=> $accountType]);
instead of
json_encode(['accountType'=> [(object)$accountType]]);
In your code you are putting $accountType inside another array that is why you are getting that result
Here is a Demo and Explanation
Edit: The entire code
$setting['accountType']['all'] = 'ALL';
$setting['accountType']['A1'] = 'VIP1';
$setting['accountType']['A2'] = 'VIP2';
$myArray = array();
foreach ($setting['accountType'] as $key => $val)
{
$object = new stdClass(); // Note: $object should be created inside the loop
$object->id = $key;
$object->desc = $val;
$myArray[] = $object;
}
$accountType = $myArray;
echo json_encode(['accountType'=> $accountType]);
And Here is the Revised Demo
Try this,
echo json_encode(array_values($your_array));
Let me know if its working
This is exactly the same thing, no?
The numerotation is displayed because you need it to access to the specific json object.
You have an array and you can access to each element by its key.

PHP Save nested json to mysql database

I have some json data that i am retrieving from an external url. It is not importing correctly unless i take out some of the brackets. Anyone know how to properly import this json data? I don't really need the "success", "num_items", "build time" and "updated at". Im a noobie. Thanks!
Here is the php
$filename = "http://www.someurl.com/data.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);
foreach($array as $row)
{
$sql = "INSERT INTO table_all_items(name, quality) VALUES (
'".$row["name"]."',
'".$row["quality"]."'
)";
mysqli_query($connect, $sql);
}
Here is data.json
{
"success": true,
"num_items": 7312,
"items": [
{
"name": "Net",
"quality": "New"
},
{
"name": "Ball",
"quality": "New"
},
{
"name": "Hoop",
"quality": "Used"
}
],
"build_time": 320,
"updated_at": 15680
}
You were looping through the wrong element of your array.
As you want to list the items, your loop must look like :
foreach($array["items"] as $row)
//$filename = "http://www.someurl.com/data.json";
//$data = file_get_contents($filename);
$data='{
"success": true,
"num_items": 7312,
"items": [
{
"name": "Net",
"quality": "New"
},
{
"name": "Ball",
"quality": "New"
},
{
"name": "Hoop",
"quality": "Used"
}
],
"build_time": 320,
"updated_at": 15680
}';
$array = json_decode($data, true);
$sql = "INSERT INTO table_all_items(name, quality) VALUES ";
foreach($array["items"] as $row)
{
$sql = $sql." (
'".$row["name"]."',
'".$row["quality"]."'
),";
}
mysqli_query($connect, substr($sql,0,-1));
I also updated the sql query, for it sends only one request with many values, instead on many requests with one value.

access to properties of an array contain json formatted elements in laravel

suppose I have an Array like this :
$myArray =
[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]
Each element of array has json format. and now I want to get name of element that have id of 87 for example.
Firstly How can I found that is there element with this id then get name property of that?
Decode JSON string into array. Then use Laravel's array_first method.
<?php
$myArray = '[{"id": 86,"name": "admin/login"},{"id": 87,"name": "admin/logout"},{"id": 88,"name": "admin/desktop"}]';
// Decode into array
$array = json_decode($myArray, true);
// Find item with correct id
$result = array_first($array, function($key, $value){
return $value['id'] === 87;
}, false);
if ($result) {
echo 'Item found, it\'s name is: '.$result['name'];
}
If you have id you like to find in variable, you have to use use construct.
// ID to search for
$searchID = 87;
// Find item with correct id
$result = array_first($array, function($key, $value) use($searchID){
return $value['id'] === $searchID;
}, false);
Try using this:
$newArray = json_decode($myArray);
and you'll get type of array
[
[
"id"=> 86,
"name"=> "admin/login"
],.....
........
]
Your $myArray is incorrect so, assuming it is a json string you can do this in the following way :
At first json_decode it into an arry.
Loop through the elements to find out you desired value(87).
Keep a flag which will tell if you have actually found any value.
<?php
$myArray =
'[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]';
$myArray = json_decode($myArray , true);
$found = 0;
foreach($myArray as $anArray)
{
if($anArray['id'] == 87)
{
var_dump($anArray['name']);
$found = 1;
}
}
if($found == 1)
{
var_dump("Element found.");
}
else
{
var_dump("Element not found. ");
}
?>

PHP Create Multidimension Array for JSON output

I feel terrible even asking because I have been TRYING to understand and comprehend other peoples examples this is what i'm TRYING to accomplish
{
"field": [
{
"appid": 0,
"page": 0,
"fieldname": "Sweet",
"value": "Tammy Howell"
},
{
"appid": 1,
"page": 1,
"fieldname": "Cecilia",
"value": "Shana Jordan"
},
{
"appid": 2,
"page": 2,
"fieldname": "Merritt",
"value": "Copeland Pena"
}
]
}
I need to be able to make the above JSON output happen when doing an SQL SELECT statement
Here is my currentCode
$x = 0;
$userFieldsResult = mysqli_query($database_id, "SELECT * FROM theDB.DynamicFields ORDER BY Page, Priority") or die (mysqli_error($database_id));
if (mysqli_num_rows($userFieldsResult)<=0)
{
echo "nothing found";
exit;
} else
{
while($row = mysqli_fetch_array($userFieldsResult))
{
$userFields[$x]['appid'] = $row['appid'];
$userFields[$x]['page'] = $row['page'];
$userFields[$x]['fieldname'] = $row['fieldname'];
$userFields[$x]['value'] = $row['value'];
$x++;
}
echo json_encode($userFields);
exit;
}
echo json_encode($userFields);
This is normally how i just been outputting json so they each are just part of 1 array looping, but I am trying to understand how to create more "in-depth" JSON arrays so they have a specific identifier before they list out the information.
[
{
"appid": 0,
"page": 0,
"fieldname": "Sweet",
"value": "Tammy Howell"
},
{
"appid": 1,
"page": 1,
"fieldname": "Cecilia",
"value": "Shana Jordan"
},
{
"appid": 2,
"page": 2,
"fieldname": "Merritt",
"value": "Copeland Pena"
}
]
In my example I just want to be able to have "field" be the "upper" part of the array that holds all the information as i showed in the example above.
You need to add field as parent array to your array.
Change from
echo json_encode($userFields);
Into
$json = array('fields' => $userFields);
echo json_encode($json);
In this particular configuration, you are being returned an object with properties, of which, the property's value may be an array.
So what you should actually be doing is creating a stdClass object in PHP and assigning it a property of "field" which is an empty array. Then you can push into this array stack.
$obj = new stdClass();
$obj->fields = array();
while(....){
$obj->fields[$x]['appid'] =
$obj->fields[$x]['appid'] = $row['appid'];
$obj->fields[$x]['page'] = $row['page'];
$obj->fields[$x]['fieldname'] = $row['fieldname'];
$obj->fields[$x]['value'] = $row['value'];
}
Now you can json encode the object and return it.
echo json_encode($obj);

Categories