从mysql中检索json数据并获取值作为对象

问题描述 投票:-1回答:4

我的数据库中有两个表(meta_key,meta_value),我使用下面的代码从数据库中获取值

$sql=mysqli_query($conn,"select * FROM tablename where meta_key='websiteurl' or meta_key='profile_photo'");

while($row=mysqli_fetch_assoc($sql))
   $output[]=$row;

上面的代码检索这样的数据

    meta_key    "profile_photo"
    meta_value  "profile_photo.jpg"
    meta_key    "websiteurl"
    meta_value  "sample.com"

我想得到这样的数据

profile_photo   "profile_photo.jpg"
websiteurl  "sample.com"

怎么做。谢谢

php
4个回答
0
投票

创建一个关联数组:

$output[$row['meta_key']] = $row['meta_value'];

0
投票

做这个 :

while($row=mysqli_fetch_assoc($sql))
{
  $output[$row['meta_key']] = $row['meta_value'];
}

0
投票

使用正确的功能。

在您的情况下,您使用返回关联数组的mysqli_fetch_assoc()

您只需要使用返回对象的函数mysqli_fetch_object()

PHP手册:http://php.net/manual/en/mysqli-result.fetch-object.php


0
投票

试试这个,希望它会起作用

while($row=mysqli_fetch_assoc($sql))
{
  $output[] = [$row['meta_key']=>$row['meta_value']];
}
© www.soinside.com 2019 - 2024. All rights reserved.