【问题标题】:How to properly encode a multi-dimensional array in php [duplicate]如何在php中正确编码多维数组[重复]
【发布时间】:2016-01-20 13:17:22
【问题描述】:

我正在尝试使用 json_encode php 函数正确创建和编码和数组。我要编码的数组是 $myarray 。从我的代码中如果这样做

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

然后
回声 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() ;
         }


        ?>

请帮忙。谢谢。

【问题讨论】:

  • 数组结构是 $myarray = Array ( [0] => Array ( [name] => Agrolait [id] => 6 ) [1] => Array ( [name] => Agrolait, Michel Fletcher [id] => 31 ) [2] => 数组 ([name] => Agrolait, Thomas Passot [id] => 30 ) )
  • 它对我有用,结果:[{"name":"Agrolait","id":6},{"name":"Agrolait, Michel Fletcher","id":31} ,{"name":"Agrolait, Thomas Passot","id":30}]
  • 关于php报错...
  • the code fails silently with no error warning. 因为页面顶部没有error_reporting on 放置error_reporting(E_ALL); ini_set('display_errors',1);
  • 你需要在这个块之前或之后检查剩余的代码。

标签: php json


【解决方案1】:

创建数组的正确方法是这样的:

$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

如果你运行代码,它工作得非常好:

[{"name":"bla","id":1},{"name":"blas","id":2}]

【讨论】:

  • 已编辑我的问题并添加了您的输入,但仍处于堆栈状态。
【解决方案2】:

您的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 字符串:

[{"name":"Agrolait","id":6},{"name":"Agrolait, Michel Fletcher","id":31},{"name":"Agrolait, Thomas Passot" ,"id":30}]

json_encode如果出错则返回值 FALSE,否则返回编码字符串。如果你检查它的结果,你至少知道它什么时候失败了。

【讨论】:

  • 已编辑我的问题并添加了更多代码。我已经按照您的建议使用 $myarray [] = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->标量()));但它似乎仍然不起作用。
  • 能否请您在$jsonstring = json_encode($myarray); 之前添加echo '&lt;pre&gt;'; var_dump($myarray); echo '&lt;/pre&gt;'; 并再次在此处发布结果?
  • 而且,您能否在声明 foreach ($customer_details as $keys =&gt; $values) 之前对 $customer_details 执行相同操作。
  • 感谢您的建议。解决了检查我的答案
【解决方案3】:

感谢您的建议已解决此问题。我的字符串数据没有按照http://nl3.php.net/manual/en/function.json-encode.php 的建议使用 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() ;
         }


          ?>

【讨论】:

    猜你喜欢
    • 2011-07-17
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    相关资源
    最近更新 更多