【问题标题】:PHP / MySQL: Print specific value from array (query result) based on its ID [duplicate]PHP / MySQL:根据其ID从数组(查询结果)中打印特定值[重复]
【发布时间】:2019-09-21 18:27:50
【问题描述】:

我使用以下 PHP 行从 MySQL 表中查询数据。 我想将查询结果存储在一个数组中,然后在同一页面上根据它们的 ID 打印来自该数组的特定值。

我是 PHP 新手,希望有人能帮助我解释我做错了什么或遗漏了什么。我假设我错误地创建了数组。

我的 PHP(相关部分,变量在本页前面已定义):

$con = mysqli_connect($host_name, $user_name, $password, $database);
$result = mysqli_query($con, "SELECT id, $col FROM $table ORDER BY id");
$rows = array();

if($result)
{
    while($row = mysqli_fetch_array($result))
    {
        print_r($row);
    } 
}
var_dump($rows);

我当前的数组(如上打印时):

Array ( [0] => testid1 [id] => testid1 [1] => testval1 [en] => testval1 ) Array ( [0] => testid2 [id] => testid2 [1] => testval2 [en] => testval2 ) Array ( [0] => testid3 [id] => testid3 [1] => testval3 [en] => testval3 ) array(0) { }

示例:
例如。我想从此数组中打印 ID = "testid2" 的项目的值。 在这种情况下,打印的值应该是“testval2”。

提前非常感谢, 迈克

【问题讨论】:

  • print_r 不创建数组,它输出数组或对象中的所有值。在您的while 中更改为$rows[] = $row;。 ...或者干脆使用php.net/manual/en/mysqli-result.fetch-all.php
  • @user3783243:谢谢。您是否有示例或链接向我展示如何创建数组以及如何从中打印值?
  • print_r($set['1']); ? print_r($set['1']['id']); ?

标签: php arrays mysqli associative-array


【解决方案1】:

将您的数据存储为:

for
(
    $set = array(); 
    $row = $result->fetch_assoc(); 
    // use value of `id` as the key in your `$set`
    $set[$row['id']] = $row
);
print_r($set);

// later:
$id = 1;
echo $set[$id]['en'];
// or
echo $set[$id][$lang];

【讨论】:

    【解决方案2】:

    您可以只使用fetch_all(),然后使用列搜索

    $con = mysqli_connect($host, $username, $password, $database);
    $result = mysqli_query($con, "SELECT id, $lang FROM $table ORDER BY id");
    $set = $result->fetch_all(MYSQLI_ASSOC);
    
    $key = array_search('testid2', array_column($set, 'id'));
    
    echo $set[$key]['en'];
    

    【讨论】:

      【解决方案3】:

      您可以使用array_combine()array_column() 将查询输出(行和列)转换为键值格式(键为id,值为en 列):

      // $set array is populated using fetch_assoc
      // create a new array using $set
      $modified_set = array_combine(array_column($set, 'id'), 
                                    array_column($set, 'en'));
      
      // Now, you can access the en value for a specific id like this:
      // eg: for id = testid2
      echo $modified_set['testid2']; // will display testval2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-12
        • 2014-10-18
        • 2021-04-24
        • 1970-01-01
        • 2022-01-10
        • 2016-10-29
        • 2022-09-30
        相关资源
        最近更新 更多