如何在php中正确编码多维数组

时间:2016-01-20 13:17:22

标签: php json

我正在尝试使用json_encode php函数正确创建和编码和数组。我想编码的数组是$ myarray。从我的代码中可以

 $myarray = array(array('name'  =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval()))  ;

然后
     echo json_encode($ myarray); //这个有效,但只有一个项目被推送到我的数组

如果我这样做

$myarray[] = array(array('name'  =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval //pushing all elements to array

结果没什么。

我错过了什么?

请参阅下面的完整代码,了解我目前所做的工作。

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


        ?>

请帮忙。谢谢。

3 个答案:

答案 0 :(得分:0)

您的foreach()循环创建一个新数组$data,其中包含与$myarray包含的相同的条目(也是数组)。所以,你可以像这样直接编码$ myarray:

<?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';
}
?>

生成此JSON字符串:

  

[{&#34;名称&#34;:&#34; Agrolait&#34;,&#34; id&#34;:6},{&#34; name&#34;:&#34; Agrolait,Michel Fletcher&#34;,&#34; id&#34;:31} ,{&#34;名称&#34;:&#34; Agrolait,Thomas Passot&#34;,&#34; id&#34;:30}]

如果出现错误,

json_encode将返回值FALSE,以及编码后的字符串else。如果你检查它的结果,你至少知道什么时候失败。

答案 1 :(得分:0)

创建数组的正确方法如下:

$myarray = array(
  array(
    'name' => 'bla',
    'id' => 1
  ),  array(
      'name' => 'blas',
      'id' => 2
    )
);

这部分代码完全没问题。

  $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

如果您运行代码,它可以正常运行:

  

[{&#34;名称&#34;:&#34; BLA&#34;&#34; ID&#34;:1},{&#34;名称&#34;:&#34; BLAS& #34;&#34; ID&#34;:2}]

答案 2 :(得分:0)

感谢你的建议解决了这个问题。根据{{​​3}}的建议,我的字符串数据未使用utf-8正确编码。检查下面的答案

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


          ?>