繁体   English   中英

在PHP中动态创建多维数组

[英]Dynamic creation of a multidimensional array in php

我正在从数据库中获取一些值,并且我需要动态创建一个多维数组,如下所示:

$found_data = 
array( 
    array('2011-11-02' => 'Mobile'),
    array('2011-11-02' => 'Mobile'),
    array('2011-11-04' => 'Mobile'),
    array('2011-11-08' => 'Desktop'),
    array('2011-11-08' => 'Mobile'),
    array('2011-11-08' => 'Mobile'),
    array('2011-11-08' => 'Mobile'),
    array('2011-11-15' => 'Mobile'),
    array('2011-11-18' => 'Mobile'),
    array('2011-11-21' => 'Desktop'),
    array('2011-11-23' => 'Mobile'),
    array('2011-11-28' => 'Desktop'),
    array('2011-11-30' => 'Mobile')
);

我在想以下方面的事情:

$found_data = array();

while($last_30_days_fetch = mysql_fetch_assoc($last_30_days_result))
{
    $hit_date = $last_30_days_fetch['hit_date'];
    $hit_device = $last_30_days_fetch['hit_device'];    
    array_push($found_data, array($clean_date=>$hit_device));

}

但是,以上代码无法正常工作。 有任何想法吗?

// 谢谢

您正在使用未定义的变量$ clean_date。 检查您的error_reporting级别,它应该报告此(未定义的变量)。

PHP允许使用[]语法将元素追加到数组。

$found_data = array();

while($last_30_days_fetch = mysql_fetch_assoc($last_30_days_result))
{
    $found_data[] = array(
        $last_30_days_fetch['hit_date'] => $last_30_days_fetch['hit_device']
    );
}

您能不能只使用:

$array[$hit_date] = $hit_device
$found_data = array();

while($last_30_days_fetch = mysql_fetch_assoc($last_30_days_result))
{
    $found_data[] = array($last_30_days_fetch['hit_date']=>$last_30_days_fetch['hit_device']);
}

为什么过度复杂化,或者如Dan所说,将其放入单个阵列中,除非需要其他数据,否则您无需使用多个阵列

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM