-2

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.

Jay's Papa
  • 103
  • 11
  • Array structure is $myarray = Array ( [0] => Array ( [name] => Agrolait [id] => 6 ) [1] => Array ( [name] => Agrolait, Michel Fletcher [id] => 31 ) [2] => Array ( [name] => Agrolait, Thomas Passot [id] => 30 ) ) – Jay's Papa Jan 20 '16 at 13:20
  • 3
    its work for me, result: [{"name":"Agrolait","id":6},{"name":"Agrolait, Michel Fletcher","id":31},{"name":"Agrolait, Thomas Passot","id":30}] – devpro Jan 20 '16 at 13:21
  • on php error reporting... – devpro Jan 20 '16 at 13:22
  • 1
    _`the code fails silently with no error warning.`_ Cause don't have `error_reporting on` place `error_reporting(E_ALL); ini_set('display_errors',1);` at the top of the page – Narendrasingh Sisodia Jan 20 '16 at 13:22
  • u need to check remaining code, either before this block or after this. – devpro Jan 20 '16 at 13:22
  • You're not actually trying to assign the values to `$myarray` the way you have it above, are you? It works just fine if you do it like this `$myarray = array(array("name" => "Agrolait", "id" => 6 ), array ("name" => "Agrolait, Michel Fletcher", "id" => 31), array("name" => "Agrolait, Thomas Passot", "id" => 30));` – Patrick Q Jan 20 '16 at 13:24
  • test with this array: ............ $myarray = array( array('name'=>'Agrolait','id'=>6), array('name'=>'Agrolait, Michel Fletcher','id'=>31), array('name'=>'Agrolait, Thomas Passot','id'=>30) ); – devpro Jan 20 '16 at 13:25
  • check the answers, i dont think issue in array structure.. – devpro Jan 20 '16 at 13:29
  • IMHO this is exactly the same question, already answered here: [http://stackoverflow.com/questions/11722059/php-array-to-json-array-using-json-encode](http://stackoverflow.com/questions/11722059/php-array-to-json-array-using-json-encode) – M.D'Urzo Jan 20 '16 at 13:31
  • Have edited my question and included some of your suggestion but still am stack. please have a look. thanks @devpro – Jay's Papa Jan 20 '16 at 15:03
  • @BonifaceIrunguh: iniliaze with $myarray = array(); instead of $myarray = null; if still not working than try header('Content-Type: application/json'); before echo json_encode.... – devpro Jan 20 '16 at 15:11

3 Answers3

0

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.

hherger
  • 1,660
  • 1
  • 10
  • 13
  • Have edited my question and added more code. I have created the array as you suggested using $myarray [] = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval())) ; but still it doesn't seem to work. – Jay's Papa Jan 20 '16 at 14:57
  • Could you please add `echo '
    '; var_dump($myarray); echo '
    ';` just before `$jsonstring = json_encode($myarray);` and publish the result here once again?
    – hherger Jan 20 '16 at 15:11
  • And, could you do the same for `$customer_details` just before the statement `foreach ($customer_details as $keys => $values) `. – hherger Jan 20 '16 at 15:20
  • thanks for your suggestion. Solved check my answer – Jay's Papa Jan 20 '16 at 15:44
0

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

Tewdyn
  • 687
  • 3
  • 16
0

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


          ?>
Jay's Papa
  • 103
  • 11