This question already has answers here:
php json_encode not working on arrays partially
(2 answers)
Closed 7 years ago.
I am trying to properly create and encode and array using json_encode php function. The array i am trying to encode is $myarray . From my code if do
$myarray = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval())) ;
then
echo json_encode($myarray) ; // this works but only one item is pushed to my array
if i do
$myarray[] = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval //pushing all elements to array
result is nothing.
what i am missing ?
see full code below on what i have so far done.
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
/*
* Retrieve available Room types.
* TODO
* make accessing ids automatic..
*/
include_once("../../openerp_models.php"); // include file to connect with openerp
date_default_timezone_set('Europe/Moscow'); // Timezone settings
//openerp connection details
require_once("../../connection.php") ;
try {
//we access partner model and domain for customers only
$customer = $connection_model->search('res.partner', 'customer', '=', TRUE);
//
//create an array
$ids = array();
//create a for loop and loop through the ids from search
for($i = 0; $i <= count($customer); $i++ )
{
// assign array values
$ids [] = $customer[$i] ;
}
// read partner with $ids
$customer_details = $connection_model->read('res.partner', $ids);
//loop through the scalavar value
$myarray = null;
// loop through the value returned
foreach ($customer_details as $keys => $values)
{
$value = $values->scalarval();
//Push values to my array
$myarray [] = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval())) ;
//
}
//Then try to encode $myrray but this fails
$jsonstring = json_encode($myarray);
if ($jsonstring!==false)
{
echo $jsonstring;
} else {
echo 'Could not properly encode $myarray';
}
///////////////////////
/////////////////////////
}
catch(Exception $ex){
print "Error ".$ex.getMessage() ;
}
?>
please help. thank you.
The right way to create the array would be like this:
$myarray = array(
array(
'name' => 'bla',
'id' => 1
), array(
'name' => 'blas',
'id' => 2
)
);
This part of your code is perfectly fine.
$data = array() ; //create new empty array
//loop through the array
foreach($myarray as $keys => $h)
{
$data [] = $h;
}
//encode
echo json_encode($data) ; //this fails silently
If you run the code, it works perfectly fine:
[{"name":"bla","id":1},{"name":"blas","id":2}]
Your foreach() loop creates a new array $data with the same entries (also arrays) as the $myarray contains. So, you could directly encode $myarray like this:
<?php
$myarray = array(
array('name' =>' Agrolait', 'id' => 6 ),
array('name' => 'Agrolait, Michel Fletcher', 'id' => 31 ),
array('name' => 'Agrolait, Thomas Passot', 'id' => 30 )
);
$jsonstring = json_encode($myarray);
if ($jsonstring!==false) {
echo $jsonstring;
} else {
echo 'Could not properly encode $myarray';
}
?>
Which produces this JSON string:
[{"name":" Agrolait","id":6},{"name":"Agrolait, Michel Fletcher","id":31},{"name":"Agrolait, Thomas Passot","id":30}]
json_encodereturns the value FALSE if something went wrong, and the encoded string else. If you check the result from it you at least know when it fails.
Thanks for your suggestion have solved this. My string data was not properly encoded using utf-8 as suggested by http://nl3.php.net/manual/en/function.json-encode.php. Check my answer below
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
/*
* Retrieve available Room types.
* TODO
* make accessing ids automatic..
*/
include_once("../../openerp_models.php"); // include file to connect with openerp
date_default_timezone_set('Europe/Moscow'); // Timezone settings
//openerp connection details
require_once("../../connection.php") ;
try {
//we access partner model and domain for customers only
$customer = $connection_model->search('res.partner', 'customer', '=', TRUE);
//
//create an array
$ids = array();
//create a for loop and loop through the ids from search
for($i = 0; $i <= count($customer); $i++ )
{
// assign array values
$ids [] = $customer[$i] ;
}
// read partner with $ids
$customer_details = $connection_model->read('res.partner', $ids);
//loop through the scalavar value
$myarray = null;
// loop through the value returned
foreach ($customer_details as $keys => $values)
{
$value = $values->scalarval();
$myarray [] = array('name' =>utf8_encode($value['display_name']->scalarval()),'id' => utf8_encode($value['id']->scalarval())) ;
//
//array_push($better, $myarray) ;
}
//echo '<pre>';
//print_r($myarray) ;
//echo '</pre>';
echo json_encode($myarray);
exit;
}
catch(Exception $ex){
print "Error ".$ex.getMessage() ;
}
?>
Related
I am getting some extra slashes while making json array using PHP. My code is below.
<?php
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001","subject"=>"Mathematics"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002","subject"=>"History"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001","subject"=>"Geology"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA003","subject"=>"Science"));
$result = []; // Initialize result array
foreach ($output as $key => $value) {
$name = $value['first_name'] . ' ' . $value['last_name'];
// check if same name already has entry, create one if not
if (!array_key_exists($name, $result)) {
$result[$name] = array(
'reg_no' => $value['reg_no'],
'name' => $name,
'paper1' => '',
'paper2' => '',
'paper3' => '',
'paper4' => ''
);
}
// count array elements with value, then set paper number and value
$paper = 'paper' . (count(array_filter($result[$name])) - 1);
$result[$name][$paper] = $value['paper_code'].'/'.$value['subject'];
}
$result = array_values($result); // reindex result array
echo json_encode($result);exit;
?>
Here the json output is given below.
[{"reg_no":12,"name":"robin sahoo","paper1":"BA001\/Mathematics","paper2":"BA002\/History","paper3":"BA003\/Science","paper4":""},{"reg_no":13,"name":"Rama Nayidu","paper1":"BA001\/Geology","paper2":"","paper3":"","paper4":""}]
Here my problem is I am adding $value['paper_code'].'/'.$value['subject']; and in output I am getting "BA001\/Mathematics". Here One extra slash(\) is added which I need to remove.
You can add JSON_UNESCAPED_SLASHES as the second parameter. LIke:
$result = array_values($result); // reindex result array
echo json_encode($result,JSON_UNESCAPED_SLASHES);exit;
This will result to:
[{"reg_no":12,"name":"robin sahoo","paper1":"BA001/Mathematics","paper2":"BA002/History","paper3":"BA003/Science","paper4":""},{"reg_no":13,"name":"Rama Nayidu","paper1":"BA001/Geology","paper2":"","paper3":"","paper4":""}]
Doc: json_encode()
I have an php file that gives me the response i need as a string, i need it to be an array encoded in json, im not that good with php, can any one help ?
this is how it works fine as a string
- printf("user: \"%s\" \"%s\" email: \"%s\" \n", $row['firstname'], $row['lastname'],$row['email']);
But i need it as an array in json that is how i tried to do it
-array_push($mynewArray,array("firstname \%s"=>$row['firstname'],"lastname \%s"=>$row['lastname'],"email \%s"=>$row['email']));
echo json_encode($mynewArray);
this is the screen shot that shows how i tried to do it
I think you could try like this assuming the recordset is generated correctly and available in the var $row
$mynewArray=array();
foreach($result as $row){
$mynewArray[]=$row;
}
echo json_encode($mynewArray);
Or
$mynewArray=array();
foreach( $result as $row ){
$mynewArray[]=array(
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'email'=>$row['email'],
);
}
echo json_encode($mynewArray);
This might be what you're after:
<?php
$cluster = Cassandra::cluster()
->build();
$keyspace = 'msata';
$session = $cluster->connect($keyspace);
$result = $session->execute(new Cassandra\SimpleStatement
("SELECT * FROM msata.users")
);
// Create the variable array here so it's used correctly in the loop
$mynewArray = array();
foreach( $result as $row ){
// Create an array for each individual user
$user_array = array( 'firstname' => $row['firstname'], 'lastname' => $row['lastname'], 'email' => $row['lastname'] );
// Add the array to the main array
$mynewArray = array_push( $mynewArray, $user_array );
}
echo json_encode( $mynewArray );
I'm a newbie here so please be with. I'm pretty sure that my code and syntax is correct.
This is my json file
{"data":
[
{"label":"Signed-in Client","value":2
}
]
}
This is my php code
<?php
$conn=mysqli_connect("localhost", "root","","something");
$res1 = mysqli_query($conn, "SELECT * FROM tbl_pet_owner ORDER BY pet_owner_id");
$max1 = mysqli_num_rows($res1);
$jsonString = file_get_contents('data.json');
$data1 = json_decode($jsonString, true);
foreach ($data1['data'] as $key )
{
if ($key[0]['label'] == "Signed-in Client")
{
$data1['value'] = $max1;
}
}
$newJsonString = json_encode($data1);
file_put_contents('data.json', $newJsonString);
?>
but when I refresh, it doesn't update with the max count of my query. I hope you'd help me. This is for my thesis
It seems to me that the problem is connected with the way how you traverse the data.
For example in foreach ($data1['data'] as $key ), $key is already an associative array (e.g., array("label" => "Signed-in Client", "value" => 2)), so instead of $key[0]['label'], one should use just $key['label'].
Also, when you want to modify the 'value', one has to access the same associative array, not the original variable $data1.
One way to achieve this would be as shown below. In that example the array $data1['data'] is traversed using references (&$key). Note that one should then unset this variable after the foreach block to break its association with the last element of the array being traversed.
<?php
$max1 = 100;//just an example
$jsonString = file_get_contents('data.json');
$data1 = json_decode($jsonString, true);
foreach ($data1['data'] as &$key )
{
print_r($key);
if($key['label'] == "Signed-in Client")
{
$key['value'] = $max1;
}
}
unset($key);
print_r($data1);
/* gives:
Array
(
[data] => Array
(
[0] => Array
(
[label] => Signed-in Client
[value] => 100
)
)
)
*/
//$newJsonString = json_encode($data1);
//file_put_contents('data.json', $newJsonString);
?>
I have a variable $a='san-serif' and an array Font_list[] now I want only the arrays whose category is 'san-serif' will be filtered. I tried a lot of codes nothing seems working here is my code:-
public function filterFont() {
$a = $_POST['key'];
$url = "https://www.googleapis.com/webfonts/v1/webfonts?key=''";
$result = json_decode(file_get_contents( $url ));
$font_list = "";
foreach ( $result->items as $font )
{
$font_list[] = [
'font_name' => $font->family,
'category' => $font->category,
'variants' => implode(', ', $font->variants),
// subsets
// version
// files
];
}
$filter = filter($font_list);
print_r(array_filter($font_list, $filter));
}
Please help me :-(
What i understood according to that you want something like below:-
<?php
$a='san-serif'; // category you want to search
$font_list=Array('0'=>Array('font_name' => "sans-sherif",'category' => "san-serif"),'1'=>Array('font_name' => "times-new-roman",'category' => "san-serif"),'2'=>Array('font_name' => "sans-sherif",'category' => "roman"));
// your original array seems something like above i mentioned
echo "<pre/>";print_r($font_list); // print original array
$filtered_data = array(); // create new array
foreach($font_list as $key=>$value){ // iterate through original array
if($value['category'] == $a){ // if array category name is equal to serach category name
$filtered_data[$key] = $value; // assign that array to newly created array
}
}
echo "<pre/>";print_r($filtered_data); // print out new array
Output:- https://eval.in/597605
Here is example how my array should look like:
$library = array(
'book' => array(
array(
'authorFirst' => 'Mark',
'authorLast' => 'Twain',
'title' => 'The Innocents Abroad'
),
array(
'authorFirst' => 'Charles',
'authorLast' => 'Dickens',
'title' => 'Oliver Twist'
)
)
);
When I get results from oracle database:
$row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS);
But when I execute my code I only get one row.
For example: <books><book></book><name></name></books>
But I want all rows to be shown in xml.
EDIT:
This is my class for converting array to xml:
public static function toXml($data, $rootNodeName = 'data', &$xml=null)
{
// turn off compatibility mode as simple xml throws a wobbly if you don't.
if (ini_get('zend.ze1_compatibility_mode') == 1)
{
ini_set ('zend.ze1_compatibility_mode', 0);
}
if (is_null($xml))
{
$xml = simplexml_load_string("<".key($data)."/>");
}
// loop through the data passed in.
foreach($data as $key => $value)
{
// if numeric key, assume array of rootNodeName elements
if (is_numeric($key))
{
$key = $rootNodeName;
}
// delete any char not allowed in XML element names
$key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);
// if there is another array found recrusively call this function
if (is_array($value))
{
// create a new node unless this is an array of elements
$node = ArrayToXML::isAssoc($value) ? $xml->addChild($key) : $xml;
// recrusive call - pass $key as the new rootNodeName
ArrayToXML::toXml($value, $key, $node);
}
else
{
// add single node.
$value = htmlentities($value);
$xml->addChild($key,$value);
}
}
// pass back as string. or simple xml object if you want!
return $xml->asXML();
}
// determine if a variable is an associative array
public static function isAssoc( $array ) {
return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
}
}
?>
Now with below responde I have tried problem is I get following output: <book>...</book> tags after each row.. then I tried 3 dimensional array now I get: <book><book>...</book></book> on the proper place but I have 2 of them.
This is the line where I have determine which is root on that array and that's why I get this output. But don't know how to change it : $xml = simplexml_load_string("<".key($data)."/>");
Thank you.
oci_fetch_array() will always return a single row, you need to call it until there are no more rows to fetch in order to get all of them:
while ($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS))
{
$library['book'][] = $row;
}