既然你不願意採取簡單的方法,並修改數據庫查詢中使用別名:
$result=mysqli_query($link,$qry);
while($obj = mysqli_fetch_object($result))
{
if (isset($obj->id_a)) {
$obj->id = $obj->id_a;
unset($obj->id_a);
} elseif (isset($obj->id_b)) {
$obj->id = $obj->id_b;
unset($obj->id_b);
} elseif (isset($obj->id_c)) {
$obj->id = $obj->id_c;
unset($obj->id_c);
}
$arr[] = $obj;
}
echo '{"results":'.json_encode($arr).'}'
編輯
$objects = array();
$object1 = new stdClass();
$object1->id_a = 1;
$object1->title = "Title 1";
$object2 = new stdClass();
$object2->id_b = 2;
$object2->title = "Title 2";
$objects[0] = $object1;
$objects[1] = $object2;
foreach($objects as $obj) {
if (isset($obj->id_a)) {
$obj->id = $obj->id_a;
unset($obj->id_a);
} elseif (isset($obj->id_b)) {
$obj->id = $obj->id_b;
unset($obj->id_b);
} elseif (isset($obj->id_c)) {
$obj->id = $obj->id_c;
unset($obj->id_c);
}
var_dump($obj);
}
給
object(stdClass)[1]
public 'title' => string 'Title 1' (length=7)
public 'id' => int 1
object(stdClass)[2]
public 'title' => string 'Title 2' (length=7)
public 'id' => int 2
爲什麼不修改數據庫的查詢別名ID_A爲ID,等? – 2013-03-11 09:50:27
我忘了寫我不想搞砸查詢。有什麼方法可以替換數組鍵嗎?我的意思是必須有... – 2013-03-11 09:52:20
有,但DB查詢別名會更容易 – 2013-03-11 09:54:44