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 查询正在确定我将收到哪些变体,因此我需要检查什么是键名并将其更改为idonly。

所以我需要检查类似 if('key'==id_a || 'key'==id_b || 'key'==id_c )将“密钥”更改为id

4

3 回答 3

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
于 2013-03-11T09:57:12.180 回答
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);
于 2013-03-11T10:02:26.380 回答
0

既然你想改变钥匙的名字,

$i=0;
foreach(mysqli_fetch_object($result) as $key=>$value) {
        $arr[$key."_".$i] = $value;
        $i++;
}
echo '{"results":'.json_encode($arr).'}';
于 2013-03-11T10:07:42.127 回答