【问题标题】:PHP: Replace values in mySQL result arrayPHP:替换 mySQL 结果数组中的值
【发布时间】:2020-11-15 17:55:00
【问题描述】:

我正在尝试替换 $data 数组中以下结果集的部分内容,例如我想用千位分隔符格式化价格并添加可变超链接而不是详细信息。

查询本身有效,我知道如何根据需要修改值,但我不知道如何替换数组中的值,或者最好只将修改后的值传递给数组。

注意:我需要在 PHP 中执行此操作(而不是直接在 mySQL 中)。

$stmt = $conn->prepare("SELECT itemId, price, details FROM offers WHERE itemId LIKE 'DE%' ORDER BY itemId");
$stmt->execute();
$resultX = $stmt->get_result(); 
$rowCountX = $resultX->num_rows;
$data = array();

while($rows = $resultX->fetch_assoc()) {
    $data[] = $rows; // array that I want to change
}

更新:

示例:
itemId: b500 -> 应该是 b500 // 不变
价格: 1500 -> 应该是1,500
详情: 项目 123 -> Item 123

有人可以帮我解决这个问题吗?

谢谢, 汤姆

【问题讨论】:

  • 能不能添加样例输入输出。
  • @aviboy2006:谢谢。这是一个普遍的问题,但我提供了一些示例。

标签: php arrays associative-array


【解决方案1】:

不确定我是否理解这个问题,但如果您想在“显示”之前更改值,或者返回查看,请在您的代码上执行以下操作:

$stmt = $conn->prepare("SELECT itemId, price, details FROM offers WHERE itemId LIKE 'DE%' ORDER BY itemId");
$stmt->execute();
$resultX = $stmt->get_result(); 
$rowCountX = $resultX->num_rows;
$data = array();
$rows = $resultX->fetch_all(MYSQLI_ASSOC);
foreach($rows as $row) {
    $row['price'] =  number_format( $row['price'] , 2 , "" , "," );
    $row['details'] = '<a href="#linkhere">'.$row['details'].'</a>';
    $data[] = $row; // array that I want to change
}

【讨论】:

    【解决方案2】:

    你可以这样做: $data = 数组();

    while($rows = $resultX->fetch_assoc()) {
        $input_data = array();
        $input_data['price']= formatIndian($rows['price']);
        $input_data['details']= "<a href='' > ". $row['details']."</a>";
        $data[]= $input_data;
    }
    

    注意formatIndian它只是将数字转换为印度格式的任何功能

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-29
      • 2012-10-03
      • 2013-10-12
      • 2021-04-06
      • 2019-03-13
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      相关资源
      最近更新 更多