I have a array like this:
Array
(
[0] => Chat Show
[1] => Non-fiction
[2] => Inspirational
)
And i am trying to get this format:
"genres": [
{
"name": "Chat Show"
},
{
"name": "Non-fiction"
},
{
"name": "Inspirational"
}
]
but i get something like this:
genres": [
"Chat Show",
"Non-fiction",
"Inspirational"
]
This is what i am doing:
while($row = mysqli_fetch_array($Data))
{
$Genres = explode('/', filter_var(rtrim($row['genres'], '/'), FILTER_SANITIZE_URL));
}
and then this is part of a bigger array
"genres" => $Genres
print_r(
json_encode(["genres" => array_map(
function($v) { return ['name' => $v]; },
$Genres)]));
result
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]}
For example, here is your array in PHP
$var = array(
"Chat Show",
"Non-fiction" ,
"Inspirational"
);
Without a key "name". You should create a new array and push each element as an array to your new array.
$result = array();
foreach($var as $name)
{
$arr = array("name"=>$name);
array_push($result, $arr);
}
after that, encode your $result by using json_encode
$json = json_encode($result,true);
echo $json;
Here is my output by echo $json.
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
Try this:
$Genres=array("Chat Show","Non-fiction","Non-fiction");
$new["genres"]=array();
foreach($Genres as $key => $name){
$new["genres"][$key] = ['name' => $name];
}
echo json_encode($new);
Output
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Non-fiction"}]}
The json string you posted here is not a valid json OR is part of json.
So, you might already have genres in your javascript, and want to get the remaining thing, which is
[
{ "name": "Chat Show" },
{ "name": "Non-fiction" },
{ "name": "Inspirational" }
]
Your current PHP $Genres looks like this because you are exploding the string
$Genres = [ 'Chat Show', 'Non-fiction', 'Inspirational' ];
Apply this to change values of your current $Genres
array_walk($Genres, function(&$v){ $v = ['name'=>$v]; });
Use it in your javascript like,
"genres": <?php json_encode($Genres)?>
Try this:
$genres_new['name']=$Genres;
echo json_encode($genres_new);
Your problem is, that you have simple array of strings, but you want an associative multilevel array. This is an relative simple operation. First lets illustrate the problem with some code:
// That is what you have, an :
$Genres = [
"Chat Show",
"Non-fiction",
"Inspirational",
];
// or the same for php > 5.4:
$Genres = array(
"Chat Show",
"Non-fiction",
"Inspirational",
);
This will produce the following json string (echo json_encode($Genres);):
["Chat Show","Non-fiction","Inspirational"]
But if you want such an output:
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
You have to convert the strings into an array. You can do that with that (or a similar loop):
foreach($Genres as $key => $name){
$Genres[$key] = ['name' => $name];
}
After that your array look like this:
Array (
0 =>
array (
'name' => 'Chat Show',
),
1 =>
array (
'name' => 'Non-fiction',
),
2 =>
array (
'name' => 'Inspirational',
),
)
Putting things together you will get something like that:
<?php
// Do whatever is necessary to build your Genres array ...
$Genres = [
"Chat Show",
"Non-fiction",
"Inspirational",
];
// Convert the array into an array of arrays
foreach($Genres as $key => $name){
$Genres[$key] = ['name' => $name];
}
echo json_encode($Genres);
/**
Now you will get this output:
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
*/
// After that you can add it to the bigger array:
$biggerArray = [];
$biggerArray['genres'] = $Genres;
echo json_encode($biggerArray);
/**
Output:
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]}
*/
Related
From PHP code I want to create an json array:
[
{"region":"valore","price":"valore2"},
{"region":"valore","price":"valore2"},
{"region":"valore","price":"valore2"}
]
How can I do this?
Easy peasy lemon squeezy: http://www.php.net/manual/en/function.json-encode.php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
There's a post by andyrusterholz at g-m-a-i-l dot c-o-m on the aforementioned page that can also handle complex nested arrays (if that's your thing).
Use PHP's native json_encode, like this:
<?php
$arr = array(
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
)
);
echo json_encode($arr);
?>
Update: To answer your question in the comment. You do it like this:
$named_array = array(
"nome_array" => array(
array(
"foo" => "bar"
),
array(
"foo" => "baz"
)
)
);
echo json_encode($named_array);
Simple: Just create a (nested) PHP array and call json_encode on it. Numeric arrays translate into JSON lists ([]), associative arrays and PHP objects translate into objects ({}). Example:
$a = array(
array('foo' => 'bar'),
array('foo' => 'baz'));
$json = json_encode($a);
Gives you:
[{"foo":"bar"},{"foo":"baz"}]
Best way that you should go every time for creating json in php is to first convert values in ASSOCIATIVE array.
After that just simply encode using json_encode($associativeArray). I think it is the best way to create json in php because whenever we are fetching result form sql query in php most of the time we got values using fetch_assoc function, which also return one associative array.
$associativeArray = array();
$associativeArray ['FirstValue'] = 'FirstValue';
...
etc.
After that.
json_encode($associativeArray);
also for array you can use short annotattion:
$arr = [
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
]
];
echo json_encode($arr);
That's how I am able to do with the help of solution given by #tdammers below.
The following line will be placed inside foreach loop.
$array[] = array('power' => trim("Some value"), 'time' => "time here" );
And then encode the array with json encode function
json_encode(array('newvalue'=> $array), 200)
Just typing this single line would give you a json array ,
echo json_encode($array);
Normally you use json_encode to read data from an ios or android app. so make sure you do not echo anything else other than the accurate json array.
I created a crude and simple jsonOBJ class to use for my code. PHP does not include json functions like JavaScript/Node do. You have to iterate differently, but may be helpful.
<?php
// define a JSON Object class
class jsonOBJ {
private $_arr;
private $_arrName;
function __construct($arrName){
$this->_arrName = $arrName;
$this->_arr[$this->_arrName] = array();
}
function toArray(){return $this->_arr;}
function toString(){return json_encode($this->_arr);}
function push($newObjectElement){
$this->_arr[$this->_arrName][] = $newObjectElement; // array[$key]=$val;
}
function add($key,$val){
$this->_arr[$this->_arrName][] = array($key=>$val);
}
}
// create an instance of the object
$jsonObj = new jsonOBJ("locations");
// add items using one of two methods
$jsonObj->push(json_decode("{\"location\":\"TestLoc1\"}",true)); // from a JSON String
$jsonObj->push(json_decode("{\"location\":\"TestLoc2\"}",true));
$jsonObj->add("location","TestLoc3"); // from key:val pairs
echo "<pre>" . print_r($jsonObj->toArray(),1) . "</pre>";
echo "<br />" . $jsonObj->toString();
?>
Will output:
Array
(
[locations] => Array
(
[0] => Array
(
[location] => TestLoc1
)
[1] => Array
(
[location] => TestLoc2
)
[2] => Array
(
[location] => TestLoc3
)
)
)
{"locations":[{"location":"TestLoc1"},{"location":"TestLoc2"},{"location":"TestLoc3"}]}
To iterate, convert to a normal object:
$myObj = $jsonObj->toArray();
Then:
foreach($myObj["locations"] as $locationObj){
echo $locationObj["location"] ."<br />";
}
Outputs:
TestLoc1 TestLoc2 TestLoc3
Access direct:
$location = $myObj["locations"][0]["location"];
$location = $myObj["locations"][1]["location"];
A practical example:
// return a JSON Object (jsonOBJ) from the rows
function ParseRowsAsJSONObject($arrName, $rowRS){
$jsonArr = new jsonOBJ($arrName); // name of the json array
$rows = mysqli_num_rows($rowRS);
if($rows > 0){
while($rows > 0){
$rd = mysqli_fetch_assoc($rowRS);
$jsonArr->push($rd);
$rows--;
}
mysqli_free_result($rowRS);
}
return $jsonArr->toArray();
}
I have a PHP array built with a while loop. I do successfully convert it to JSON string, however the output is not what I want and need some help to get it right:
My current code:
while(!$sql_query->EOF){
$data[] = array(
'id' => $id,
'name' => $name,
'title' => $title
);
$sql_query-> MoveNext(); }
echo json_encode($data);
The output I get with my code is this:
[
{
"id":"1",
"name":"Nick",
"title":"Office"
},
{
"id":"2",
"name":"Amy",
"title":"Home"
}
]
However, I need the outcome to be:
{
"data": [
[
"1",
"Nick",
"Office"
],
[
"2",
"Amy",
"Home"
]
]
}
I tired paying around with array_values() but no success so far.
Can somebody suggest the right approach here?
When building your array, don't add the keys to the values, this will allow the encoding to use array notation, then add the "data" key as part of the encode...
$data = [];
while(!$sql_query->EOF){
$data[] = [ $id, $name,$title];
$sql_query-> MoveNext();
}
echo json_encode(["data" => $data]);
If you do something like:
$result = (object)["data" => $data];
echo json_encode($data);
this will give you the output you require.
First of all you have to modify you array
$newData = [];
foreach($data as $item) {
$newData[] = array_values($item);
}
and then create new array
echo json_encode(["data"=>$newData])
I have one array, in this array values, i want to push object wise,how can do this?
print_r($_POST['amenity_check']);
Array
(
[0] => Gym
[1] => Swimming Pool
)
Expected Results
"amenities": [
{
"amenity_name":"Gym"
},
{
"amenity_name":"Swimming Pool"
}
],
]
You can try the following:
$output = [];
foreach ($_POST['amenity_check'] as $value)
{
$output[] = [
'amenity_name' => $value
];
}
echo json_encode([
"amenities" => $output
]);
Output:
{"amenities":[{"amenity_name":"Gym"},{"amenity_name":"Swimming Pool"}]}
This uses a foreach loop to get the desired output as array, and the uses json_encode to turn it into a json string.
I have the below code in a for..loop is there a way I can add values to the beginning of the array?
$data = array();
$initial = strtotime('11:00:00');
for (; $initial < strtotime("23:00:59"); $initial = strtotime("+15 minutes", $initial)) {
if ($initial > strtotime("+45 minutes", time())) {
$row['value'] = date('Hi', $initial);
$row['label'] = date('H:i', $initial);
$data['data'][] = $row;
}
}
I want to add the below values to the top of the array. I have tried using array_unshift but I don't think it supports key-value pairs.
if(!isBetween('22:00', '09:59', date('H:i'))) {
$row['value'] = "asap";
$row['label'] = "ASAP";
}
My array output
{
"data": [
{
"value": "1145",
"label": "11:45"
}
]
}
I want to get this
{
"data": [
{
"value": "asap",
"label": "ASAP"
},{
"value": "1145",
"label": "11:45"
},
]
}
Un-shift should work if you pass the arguments correctly:
array_unshift($data["data"], $prepend);
Alternatively, you could use array_merge, like this:
$data["data"] = array_merge(array($prepend), $data["data"]);
With the following example data:
$data = [
"data" => [
[
"value" => "1145",
"label" => "11:45"
]
]
];
$prepend = [
"value" => "asap",
"label" => "ASAP"
];
$data["data"] = array_merge(array($prepend), $data["data"]);
print_r($data);
You would get this output (with both solutions):
Array (
[data] => Array (
[0] => Array (
[value] => asap
[label] => ASAP
)
[1] => Array (
[value] => 1145
[label] => 11:45
)
)
)
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:
function array_unshift_assoc(&$arr, $key, $val) {
$arr = array_reverse($arr, true);
$arr[$key] = $val;
return array_reverse($arr, true);
}
Source: http://php.net/manual/en/function.array-unshift.php
Here a have a json string, and need to get all the parent array positions of registratition_id
E.g. i want the array at the end to out put something like this:
[0] =>0
[1] =>1
[2] =>3
In fact I want to get all the arrays position which contain registration_id
$json_raw = '{"multicast_id":6446899316497614986,
"success":5,
"failure":1,
"canonical_ids":3,
"results":[
{"registration_id":"APA91bEgLFvrc0lnXqX3C1euQohdHrv_wbxtGP86ezRzGWEVMQPpJjw1GMhGzfkI8Q34TU1KRts2j_-7CyU4ce6MlX5DB3umpXDGl-Ebmg53b44UKga79ee9Sal6gT_9rP3KIz9pDEUk2JVJsQmxiWXWoIfrYEAmFg",
"message_id":"0:1396175384218906%50b5570df9fd7ecd"
},
{"registration_id":"APA91bEgLFvrc0lnXqX3C1euQohdHrv_wbxtGP86ezRzGWEVMQPpJjw1GMhGzfkI8Q34TU1KRts2j_-7CyU4ce6MlX5DB3umpXDGl-Ebmg53b44UKga79ee9Sal6gT_9rP3KIz9pDEUk2JVJsQmxiWXWoIfrYEAmFg",
"message_id":"0:1396175384218155%50b5570df9fd7ecd"
},
{"message_id":"0:1396175384218718%b91f4d1ff9fd7ecd"
},
{"registration_id":"APA91bEgLFvrc0lnXqX3C1euQohdHrv_wbxtGP86ezRzGWEVMQPpJjw1GMhGzfkI8Q34TU1KRts2j_-7CyU4ce6MlX5DB3umpXDGl-Ebmg53b44UKga79ee9Sal6gT_9rP3KIz9pDEUk2JVJsQmxiWXWoIfrYEAmFg",
"message_id":"0:1396175384219100%50b5570df9fd7ecd"
},
{"message_id":"0:1396175384219927%50b5570df9fd7ecd"
},
{"error":"InvalidRegistration"
}]
}';
Use a foreach loop and check if registration_id isset
$obj = json_decode($json_raw);
$resultsWithRegID = array();
foreach($obj->results as $index=>$element){
if(isset($element->registration_id)){
$resultsWithRegID[] = $index;
}
}
Just an alternative version:
$array_raw = json_decode($json_raw, true);
$what = "registration_id";
$res = array_keys(array_filter($array_raw['results'], function($item) use ($what)
{
return isset($item[$what]);
}));
var_dump($res);
Obviously you can:
define the key to search straight inside the isset($item["registration_id"])
omit the wrapping function array_keys if you need the whole part of the array filtered
(whole part)
array (size=3)
0 =>
array (size=2)
'registration_id' => 'APA91bEgLFvrc0lnXqX3C1euQohdHrv...'
'message_id' => ''
1 =>
array (size=2)
'registration_id' => 'APA91bEgLFvrc0lnXqX3C1euQohdHrv...'
'message_id' => '0:1396175384218155%50b5570df9fd7ecd'
3 =>
array (size=2)
'registration_id' => 'APA91bEgLFvrc0lnXqX3C1euQohdHrv...'
'message_id' => '0:1396175384219100%50b5570df9fd7ecd'
<html>
<head>
<title>Online PHP Script Execution</title>
</head>
<body>
<?php
$json_raw = '{"multicast_id":6446899316497614986,
"success":5,
"failure":1,
"canonical_ids":3,
"results":[
{"registration_id":"APA91bEgLFvrc0lnXqX3C1euQohdHrv_wbxtGP86ezRzGWEVMQPpJjw1GMhGzfkI8Q34TU1KRts2j_-7CyU4ce6MlX5DB3umpXDGl-Ebmg53b44UKga79ee9Sal6gT_9rP3KIz9pDEUk2JVJsQmxiWXWoIfrYEAmFg",
"message_id":"0:1396175384218906%50b5570df9fd7ecd"
},
{"registration_id":"APA91bEgLFvrc0lnXqX3C1euQohdHrv_wbxtGP86ezRzGWEVMQPpJjw1GMhGzfkI8Q34TU1KRts2j_-7CyU4ce6MlX5DB3umpXDGl-Ebmg53b44UKga79ee9Sal6gT_9rP3KIz9pDEUk2JVJsQmxiWXWoIfrYEAmFg",
"message_id":"0:1396175384218155%50b5570df9fd7ecd"
},
{"message_id":"0:1396175384218718%b91f4d1ff9fd7ecd"
},
{"registration_id":"APA91bEgLFvrc0lnXqX3C1euQohdHrv_wbxtGP86ezRzGWEVMQPpJjw1GMhGzfkI8Q34TU1KRts2j_-7CyU4ce6MlX5DB3umpXDGl-Ebmg53b44UKga79ee9Sal6gT_9rP3KIz9pDEUk2JVJsQmxiWXWoIfrYEAmFg",
"message_id":"0:1396175384219100%50b5570df9fd7ecd"
},
{"message_id":"0:1396175384219927%50b5570df9fd7ecd"
},
{"error":"InvalidRegistration"
}]
}';
$data=json_decode ($json_raw);
$arr= $data->{'results'};
$i=0;
$n_r=array();
foreach($arr as $d)
{$n_r[]=$arr[$i]->{'registration_id'};
$i=$i+1;}
print_r($n_r);
?>
</body>
</html>
Convert JSON to Array - Rest is yours:
$array = json_decode($json_raw, true);
// results with registration_id
$results = array();
foreach($array['results'] as $index => $element) {
if(isset($element['registration_id']) === true) {
$results[] = $index;
}
}
var_dump($results);