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

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"}]

Related

Accessing Data in Array - Non-Object Error PHP

I'm populating an array like this:
$POarray = array();
foreach($orders as $order)
{
$total = OrderItems::where('OrderID', $order->OrderID)->sum('TotalPrice') * (1 + $LRmarkup);
$arraydata = array(
'Name' => $order->OrderNumber,
'Total' => $total);
$POarray[] = $arraydata;
}
This results in the contents of the $POarray variable being:
[
{
"Name": "DS-BS-18102654",
"Total": 241.4655
},
{
"Name": "test test",
"Total": "600.00"
}
]
I am attempting to access this data like this:
$purchase1name = $POarray[0]->Name;
$purchase1total = $POarray[0]->Total;
And I am getting this error:
"Trying to get property of non-object"
Shouldn't this work?
Thank you for taking the time to respond.
$POarray is not an object.
Try:
$purchase1name = $POarray[0]['Name'];
$purchase1total = $POarray[0]['Total'];
You need to do this way after decoding it using json_decode(),
<?php
$key='[
{
"Name": "DS-BS-18102654",
"Total": 241.4655
},
{
"Name": "test test",
"Total": "600.00"
}
]';
$POarray = json_decode($key);
echo $POarray[0]->Name;
echo $POarray[0]->Total;
?>
DEMO: https://3v4l.org/JvCam
You can also use this.
array_get($POarray[0], 'Name');
array_get($POarray[0], 'Total');
For more information: https://laravel.com/docs/5.7/helpers

Get seperate information about each JSON element

I've JSON as follows:
[
{
"id": "..",
"size": "..",
"task": ".."
},
{
"id": "..",
"size": "..",
"task": "..",
},
...
]
My task is to get plain JSON code for each element (array). So, for every id (seperate element) I would get it's json information (size, task ect...). How can this be done?
Update: Is there any better way than following?
json_decode and then loop over each array (because this would give me decoded version, which I don't want right now, so after this procedure, I'd have to encode result again).
Use json_decode()
<?php
$json = array(array('fname'=> "aman", 'lname' => 'kumar', 'email'=> 'developer.amankr#gmail.com'));
$data = json_encode($json); //[{"fname":"aman","lname":"kumar","email":"developer.amankr#gmail.com"}]
$parse = json_decode($data);
echo $fname = $parse[0]->fname;
echo $lname = $parse[0]->lname;
echo "<br>";
echo $email = $parse[0]->email;
?>

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.

how to add array without creating a id number?

$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);

Strange JSON output from PHP json_encode()

I'm playing with JSON using PHP. I'm using json_encode() function to create JSON. Hovewer I've got strange JSON output:
[
{
"0": "1",
"1": "test",
"2": "test",
"ID": "1",
"title": "test",
"imageUrl": "test"
},
{
"0": "2",
"1": "welcome",
"2": "http://overkiller.pl/Smokopedia/Images/01.jpg",
"ID": "2",
"title": "welcome",
"imageUrl": "http://overkiller.pl/Smokopedia/Images/01.jpg"
}
]
Why I am getting this sort JSON how to get rid these numbers from it?
My PHP code:
<?php
header('Content-type: application/json');
$connection = mysql_connect('localhost', 'root', 'sam1');
$array = array();
if($connection)
{
mysql_select_db("Smokopedia");
$result = mysql_query("Select * from mainMenu");
if($result)
{
while ($row = mysql_fetch_array($result))
{
array_push($array, $row);
}
echo json_encode($array);
}else
{
$errorJson = array(
message => 'Result is empty or incorrect',
type => 'error'
);
echo json_encode($errorJson);
}
}
mysql_close();
?>
mysql_fetch_array includes both numeric indexed keys and column name indexed keys.
Change it to mysql_fetch_assoc and you'll get the end result you need.
Note though, that the entire mysql extension is deprecated and you should consider switching to PDO or Mysqli.
The issue is you are fetching an array, which includes both numerical indexes and string keys.
Change to mysql_fetch_assoc
while ($row = mysql_fetch_ssoc($result))
Side note: the mysql_* library is deprecated. Considered upgrading to a modern API such as MySQLi or PDO.

Categories