gpt4 book ai didi

php - 更改数组中的键

转载 作者:行者123 更新时间:2023-11-29 13:59:19 24 4
gpt4 key购买 nike

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

我有类似的东西:

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

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

结果可能会出现三种变化

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

我的 sql 查询正在确定我将收到哪些变体,因此我需要检查键名是什么并将其仅更改为 id

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

最佳答案

因为您不愿意采取简单的方法并修改数据库查询以使用别名:

$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

关于php - 更改数组中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15335454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com