【问题标题】:PHP multidimensional to flat array (changing key->value)PHP多维到平面数组(更改键->值)
【发布时间】:2012-08-15 14:52:17
【问题描述】:

这是我在使用PHP查询mysql数据时经常遇到的一个问题,想知道有没有更高效的解决方案。当我只需要两列数据时,例如“id”和“price”列,我更喜欢这种“flat”格式:

array(
    id 1 => price 1,
    id 2 => price 2,
    id 3 => price 3,
    ...
);

或在 json 中:

[{"id 1":"price 1"},{"id 2":"price 2"},{"id 3":"price 3"}, ...]

我通常的解决方案是循环两次,如下所示:

require_once('server/connection.php');
$info = mysql_query("SELECT id, price FROM table");  

$array1 = array();
while ($row = mysql_fetch_assoc($info)) {
    $array1[] = array(
        'id' => $row['id'],
        'price' => $row['price']
    );
}
mysql_close($con);

$array2 = array();
foreach ($array1 as $key => $value) {
    $array2[$key][$value['id']] = $value['price'];
}

print json_encode($array2);

确实有效,但我认为这段代码对于它的目的来说太长了,应该有更好的方法——这样我只需要循环一个数组。有什么建议吗?

【问题讨论】:

  • 第二个循环:你宁愿做一个二维数组。

标签: php mysql arrays multidimensional-array


【解决方案1】:

你可以把你的循环简化成这个

while ($row = mysql_fetch_assoc($info)) {
    $array1[] = array(
        'id '.$row['id'] => 'price '.$row['price']
    );
}

print json_encode($array1);

【讨论】:

  • 谢谢,这比我想象的要简单得多!
【解决方案2】:
$result = array();
while ($row = mysql_fetch_assoc($info)) {
    $result[$row['id']] = $row['price'];
}
print_r($result);

【讨论】:

    【解决方案3】:
    require_once('server/connection.php');
    $info = mysql_query("SELECT id, price FROM table");  
    
    $array1 = array();
    while ($row = mysql_fetch_assoc($info))
        $array1[$row['id']] = $row['price'];
    mysql_close($con);
    
    print json_encode($array1);
    

    注意:您的 $array2 是一个二维数组。如果它适合您,您需要更改您的 javascript 代码以处理以下平面格式,即上述代码生成

    [{"id 1":"price 1"},{"id 2":"price 2"},{"id 3":"price 3"}, ...]
    

    【讨论】:

    • 这也很好用。感谢您指出它是一个二维数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    相关资源
    最近更新 更多