我有一个php json creater。这是一个Web服务,我在android中使用它。我有sql数据,类,并希望在clasess中运行查询。
这是我没有类的json解析器。
<?php
/$sql_query = blabla{
$dolaplar= array();
/* fetch object array */
while ($obj = $result->fetch_object()) {
// printf ("%d - %s - %s\n", $obj->id, $obj->tanim, $obj->tipi);
$dolaplar[]= $obj;
}
$kodlanmis= json_encode($dolaplar);
echo $kodlanmis;
/* free result set */
$result->close();
}
?>
这是json数据。
[
{
malzeme_id: "9",
malzeme_adi: "10 kohm direnc",
malzeme_miktari: "580"
},
{
malzeme_id: "8",
malzeme_adi: "Hdmi Kablosu",
malzeme_miktari: "128"
},
{
malzeme_id: "7",
malzeme_adi: "Kirmizi Led",
malzeme_miktari: "-653"
}
]
这是课程。
<?php
class A {
public $Message = "Success";
public $MessageInfo = "";
public $Payload = array();
function __construct(){
for ( $i=3; $i-->0;){
array_push($this->Payload, new B);
}
}
}
class B {
public $a = 3;
public $b = 4;
}
echo json_encode(new A);
?>
我希望看到这样的json数据。
{
Message: "Success",
MessageInfo: "",
Payload: [
{
malzeme_id: "9",
malzeme_adi: "10 kohm direnc",
malzeme_miktari: "580"
},
{
malzeme_id: "8",
malzeme_adi: "Hdmi Kablosu",
malzeme_miktari: "128"
},
{
malzeme_id: "7",
malzeme_adi: "Kirmizi Led",
malzeme_miktari: "-653"
}
]
}
我对php不是很了解。有可能吗?
答案 0 :(得分:2)
您可以向A类和B类构造函数添加参数:
A类:
class A {
public $Message = "Success";
public $MessageInfo = "";
public $Payload = array();
function __construct($data){
foreach ($data as $d) {
array_push($this->Payload, new B($d));
}
}
}
B类:
class B {
public function __construct($data) {
array_walk($data, function($value, $key){
$this->$key = $value;
});
}
}
然后你的电话会是这样的:
$data = $dolapla // ???
echo json_encode(new A($data));