来自 fatfree DB SQL Mapper 的处理结果,用于 json 编码
Processing results from fatfree DB SQL Mapper for json encoding
我无法将 DB SQL 映射器返回的结果处理成可识别的 json 编码数组。
function apiCheckSupplyId() {
/*refer to the model Xrefs*/
$supply_id = $this->f3->get('GET.supply_id');
$xref = new Xrefs($this->tongpodb);
$supply = $xref->getBySupplyId( $supply_id );
if ( count( $supply ) == 0 ) {
$this->logger->write('no xref found for supply_id=' .$supply_id);
$supply = array( array('id'=>0) );
echo json_encode( $supply );
} else {
$json = array();
foreach ($supply as $row){
$item = array();
foreach($row as $key => $value){
$item[$key] = $value;
}
array_push($json, $item);
}
$this->logger->write('xref found for supply_id=' .$supply_id.json_encode( $json ) );
echo json_encode( $json );
}
}
这是我正在使用的方法,但对我来说似乎很笨拙。有没有更好的方法?
假设 getBySupplyId
returns 一个 Xref
映射器数组,您可以像这样简化整个事情:
function apiCheckSupplyId() {
$supply_id = $this->f3->get('GET.supply_id');
$xref = new Xrefs($this->tongpodb);
$xrefs = $xref->getBySupplyId($supply_id);
echo json_encode(array_map([$xref,'cast'],$xrefs));
$this->logger->write(sprintf('%d xrefs found for supply_id=%d',count($xrefs),$supply_id));
}
解释:
$xrefs
变量包含一个映射器数组。每个映射器都是一个对象,在将其编码为 JSON 之前,您必须将其 cast 到一个数组。这可以通过将 $xref->cast()
方法映射到每个记录在一行中完成:array_map([$xref,'cast'],$xrefs)
.
如果您对该语法没有信心,您可以遍历每条记录并强制转换它:
$cast=[];
foreach ($xrefs as $x)
$cast[]=$x->cast();
echo json_encode($cast);
结果是一样的
使用 cast()
其他方法的优点是只读取每个值(就像您在原始脚本中所做的那样)是它还包括 virtual fields。
我无法将 DB SQL 映射器返回的结果处理成可识别的 json 编码数组。
function apiCheckSupplyId() {
/*refer to the model Xrefs*/
$supply_id = $this->f3->get('GET.supply_id');
$xref = new Xrefs($this->tongpodb);
$supply = $xref->getBySupplyId( $supply_id );
if ( count( $supply ) == 0 ) {
$this->logger->write('no xref found for supply_id=' .$supply_id);
$supply = array( array('id'=>0) );
echo json_encode( $supply );
} else {
$json = array();
foreach ($supply as $row){
$item = array();
foreach($row as $key => $value){
$item[$key] = $value;
}
array_push($json, $item);
}
$this->logger->write('xref found for supply_id=' .$supply_id.json_encode( $json ) );
echo json_encode( $json );
}
}
这是我正在使用的方法,但对我来说似乎很笨拙。有没有更好的方法?
假设 getBySupplyId
returns 一个 Xref
映射器数组,您可以像这样简化整个事情:
function apiCheckSupplyId() {
$supply_id = $this->f3->get('GET.supply_id');
$xref = new Xrefs($this->tongpodb);
$xrefs = $xref->getBySupplyId($supply_id);
echo json_encode(array_map([$xref,'cast'],$xrefs));
$this->logger->write(sprintf('%d xrefs found for supply_id=%d',count($xrefs),$supply_id));
}
解释:
$xrefs
变量包含一个映射器数组。每个映射器都是一个对象,在将其编码为 JSON 之前,您必须将其 cast 到一个数组。这可以通过将 $xref->cast()
方法映射到每个记录在一行中完成:array_map([$xref,'cast'],$xrefs)
.
如果您对该语法没有信心,您可以遍历每条记录并强制转换它:
$cast=[];
foreach ($xrefs as $x)
$cast[]=$x->cast();
echo json_encode($cast);
结果是一样的
使用 cast()
其他方法的优点是只读取每个值(就像您在原始脚本中所做的那样)是它还包括 virtual fields。