【发布时间】: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); -
你需要在这个块之前或之后检查剩余的代码。