更改数组中的键

时间:2013-03-11 09:48:58

标签: php mysql arrays json

我想更改数组中键的名称。

我有类似的东西:

$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}]
  4. 我的SQL查询正在确定我将收到哪些变体,因此我需要检查键名是什么,并将其更改为id

    所以我需要查看if('key'==id_a || 'key'==id_b || 'key'==id_c )之类的内容,将“密钥”更改为id

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);

答案 2 :(得分:0)

由于您想更改密钥的名称,

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