extract json objects from an array in php [duplicate] - php

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();
}

Related

Going trough Array in PHP

I am learning PHP and I got stuck on this part.
I need to create Array and go trough It with For loop but I got stuck. I either get Array to String conversion error or blank page.
$array = array(
array(1, "FirstName1", "LastName1", "email1#gmail.com"),
array(2, "FirstName2", "LastName2", "email2#gmail.com"),
array(3, "FirstName3", "LastName3", "email3#gmail.com"),
);
This is how my array needs to look. In what way I can use for loop to go trough it?
Also what is good way to go trough multidimensional array with string indexes like this?
$array = array(
array("ID" => 1,"fname" => "name","lname" => "name","email" => "mail#gmail.com"),
array("ID" => 2,"fname" => "name","lname" => "name","email" => "mail#gmail.com"),
array("ID" => 3,"fname" => "name","lname" => "name","email" => "mail#gmail.com")
);
So $array is an array of associated arrays. To print all values in it, do the following:
// Loop thorugh the $array
for($i=0;$i<count($array);$i++)
{
echo 'Printing '.$i.' row';
// Loop through each element of the $array
foreach($array[$i] as $key=>$value)
{
echo $key." = ".$value.PHP_EOL;
}
echo PHP_EOL;
}

php object and array

I'm trying to write to a variable inside an object and I can't find how to do it.
Array
(
[0] => stdClass Object
(
[id] => 3
[rota_name] => Tea and coffee
[rota_owner_name] => 9
[rota_notes] =>
[rota_entry] => {"rota_entry0":{"person":"8","rota_assignment_date":"2018-04-01 20:17:48","rota_role":""},"rota_entry1":{"person":"7","rota_assignment_date":"2018-04-08 20:17:48","rota_role":""},"rota_entry2":{"person":"11","rota_assignment_date":"2018-04-15 20:17:48","rota_role":""},"rota_entry3":{"person":"7","rota_assignment_date":"2018-04-22 20:17:48","rota_role":""},"rota_entry4":{"person":"10","rota_assignment_date":"2018-04-29 20:17:48","rota_role":""},"rota_entry5":{"person":"3","rota_assignment_date":"2018-05-06 20:18:20","rota_role":""},"rota_entry6":{"person":"11","rota_assignment_date":"2018-05-13 20:18:23","rota_role":""}}
[rota_advance_email_days] =>
[rota_reminder_sent] =>
)
I want to change person 8 to person 9
So I think that I need to get the rota_entry (using foreach) and then use Json_decode to get an array and then something but my brain now hurts :( I and don't know how to reset it back up to put into the database again.
I can find lots that talks about simple JSON decode or simple array parsing but not something to help with this
This code assumes $obj = the first entry in your array you show.
So $obj = Array[0]
$json = json_decode($obj->rota_entry);
$json->rota_entry0->person = 9;
$obj->rota_entry = json_encode($json);
This code changes rota_entry0 person 8 to 9
// Your original array
$array = [
0 => (object) [
'id' => 3,
'rota_name' => 'Tea and coffee',
'rota_owner_name' => 9,
'rota_notes' => '',
'rota_entry' =>' {"rota_entry0":{"person":"8","rota_assignment_date":"2018-04-01 20:17:48","rota_role":""},"rota_entry1":{"person":"7","rota_assignment_date":"2018-04-08 20:17:48","rota_role":""},"rota_entry2":{"person":"11","rota_assignment_date":"2018-04-15 20:17:48","rota_role":""},"rota_entry3":{"person":"7","rota_assignment_date":"2018-04-22 20:17:48","rota_role":""},"rota_entry4":{"person":"10","rota_assignment_date":"2018-04-29 20:17:48","rota_role":""},"rota_entry5":{"person":"3","rota_assignment_date":"2018-05-06 20:18:20","rota_role":""},"rota_entry6":{"person":"11","rota_assignment_date":"2018-05-13 20:18:23","rota_role":""}}',
'rota_advance_email_days' => '',
'rota_reminder_sent' => '',
]
];
// Create an empty object to replace the rota_entry key in the array
$rotaEntry = (object) [];
// Iterate through the original rota_entry and replace "person"
foreach (json_decode($array[0]->rota_entry) as $key => $value) {
// You can set whatever logic you want here
// For example: if ($key == "rota_entry4") {$value->person = 4;}
// I'm hardcoding "9"
$value->person = 9;
$rotaEntry->$key = $value;
}
// Assign the newly created (and modified) rotaEntry back to the original array
$array[0]->rota_entry = $rotaEntry;
Try this:
$array = (array) $object;
foreach($array as &$value){
$json = json_encode($value['rota_entry']);
$json -> rota_entry0 -> person = 9;
$value['rota_entry'] = json_encode($json);
}
$array = (object) $array;
good luck.

How to format array as key : value?

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

Creating JSON array with information retrieved from database

I am trying to create a JSON array with the information selected from a database but I cannot give the array a name.
while($row = mysql_fetch_array($result))
{
$arr = array('isim' => $row['ename'], 'yer' => $row['eplace'], 'top' => $row['society'], 'tar' => $row['edate'], 'saat' => $row['ehour']);
echo json_encode($arr);
}
I want to see the result;
{"events":[{"isim":"eere","yer":"dddd","top":"asdfsdffgdfgdfg","tar":"2013-10-18","saat":"12:46"}{"isim":"fhjfr","yer":"yhjrhj","top":"ryjryjrj","tar":"2013-10-30","saat":"12:45"}{"isim":"sfsgsg","yer":"sfgssfg","top":"sgsfgsg","tar":"2013-10-31","saat":"12:45"}]}
But I cannot see the
{"events":[
in the beggining and
]}
at the end.
Thank you.
To generate valid JSON, you first need to add everything to a multi-dimensional array and only then when that is complete, encode it:
$arr = array();
while($row = mysql_fetch_array($result))
{
$arr[] = array('isim' => $row['ename'], 'yer' => $row['eplace'], 'top' => $row['society'], 'tar' => $row['edate'], 'saat' => $row['ehour']);
// or perhaps just: $arr[] = $row;
}
echo json_encode($arr);
Also note that the mysql_* functions are deprecated.
To put everything under an events key, you would need something like:
$arr['events'][] = array('isim' => $row['ename'], 'yer' => $row['eplace'], 'top' => $row['society'], 'tar' => $row['edate'], 'saat' => $row['ehour']);

How to create an array for JSON using PHP?

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();
}

Categories