2013-03-11 55 views
0

我想更改數組中的密鑰名稱。更改陣列中的密鑰

我有類似:

$result=mysqli_query($link,$qry); 
while($obj = mysqli_fetch_object($result)) 
{ 
    $arr[] = $obj; 
} 

echo '{"results":'.json_encode($arr).'}'; 

結果可能發生在三個變化

  1. results: [{id_a:1, title:V}]
  2. results: [{id_b:1, title:V}]
  3. results: [{id_c:1, title:V}]

我的sql查詢正在確定我會收到哪些變體,因此我需要檢查密鑰名稱,並將其更改爲id

所以我需要檢查類似if('key'==id_a || 'key'==id_b || 'key'==id_c)變化的「關鍵」 id

+1

爲什麼不修改數據庫的查詢別名ID_A爲ID,等? – 2013-03-11 09:50:27

+0

我忘了寫我不想搞砸查詢。有什麼方法可以替換數組鍵嗎?我的意思是必須有... – 2013-03-11 09:52:20

+1

有,但DB查詢別名會更容易 – 2013-03-11 09:54:44

回答

1

既然你不願意採取簡單的方法,並修改數據庫查詢中使用別名:

$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 
+0

正是我需要解決這個問題!謝謝 – 2013-03-11 10:14:51

0

你可以嘗試這樣的事:

$objects = array(); 
$object1 = new stdClass(); 
$object1->id_a = 1; 
$object1->label = "label1"; 
$object2 = new stdClass(); 
$object2->id_b = 2; 
$object2->label = "label2"; 
$objects[0] = $object1; 
$objects[1] = $object2; 

foreach($objects as $object) { 
    foreach($object as $key => $value) { 
     if(strpos($key, "id") !== false) { 
      unset($object->$key); 
      $key = "id"; 
      $object->$key = $value; 
     } 
    } 
} 
print_r($objects); 
0

既然你婉改鍵的名稱,

$i=0; 
foreach(mysqli_fetch_object($result) as $key=>$value) { 
     $arr[$key."_".$i] = $value; 
     $i++; 
} 
echo '{"results":'.json_encode($arr).'}';