生成多维数组

时间:2014-10-23 10:19:24

标签: php arrays multidimensional-array

我需要在PHP中创建这种形式的多维数组:

$data = array(
'legend' => array('Series 1', 'Series 2', 'Series 3',),
'data 1' => array(10, 7, 5),
'data 2' => array(20, 60, 3),
'data 3' => array(50, 33, 7),
'data 4' => array(25, 0, 14));

但我无法动态制作它。图例将是硬编码的,但data1,data2 ......是动态的。我是一个PHP新手,我需要解决这个问题。

我已经静态制作了传奇阵列,但其余的我需要帮助!

3 个答案:

答案 0 :(得分:2)

如何使用array_unshift()

<?php

$data = array();
$headings = array('legend' => array('Series 1','Series 2','Series 3'));

$db = new PDO('mysql:host=localhost;dbname=mydb;charset=utf8', 'myuser', 'mypass');

$stmt = $db->prepare('SELECT * FROM mytable WHERE field = ?');
if($stmt->execute(array($_REQUEST['value']))){
    $i=1;
    while($row=$stmt->fetch()){
        $data[]=array('data ' . $i => array(
            $row->series1,
            $row->series2,
            $row->series3,
        ));
        $i++;
    }
}

array_unshift($data, $headings);
print_r($data);

?>

答案 1 :(得分:1)

试试这个。这是一般形式,因为你没有给出结果结构

$result = 'result from database';
$data['legend'] = array('Series 1', 'Series 2', 'Series 3');
$i = 1;
while($data = mysql_fetch_array($result))
{
$data['data'.$i] = array('asdfas','asda','asdasd');
$i+=1;
}

print_r($data);

答案 2 :(得分:0)

这样可行:

$db = mysqli_connect('host', 'username', 'password', 'database');
if (mysqli_connect_errno())
    exit("Failed to connect to database.");

$query = "SELECT * FROM tbl";
$result = mysqli_query($db, $query);
$data = array('legend' => array('Series 1','Series 2','Series 3'));
while ($row = mysqli_fetch_row($result))
    $data['data ' . count($data)] = $row;