2017-04-08 35 views
0

下面的代码给出了下面的数组,但是我需要它的格式不同(在数组之后声明),所以它对于我已经编写的javascript函数有效。在PHP中更改三维数组中的第一个数组的键

$sql = "SELECT towhich, duedate, amount FROM sales WHERE email = '$email' ORDER BY duedate ASC"; 
$result = mysqli_query($conn, $sql); 
$dbarray = array(); 
while($row = mysqli_fetch_assoc($result)) { 
    $dbarray[] = $row; 
} 


$graph = array(); 
$cnt = 0; 
foreach($dbarray as $key => $values){ 
$orderdate = explode('-', $values['duedate']); 
$month = $orderdate[1]; 
$graph[$month][$cnt] = array (
0 => $values['amount'], 
1 => $values['towhich'] 
); 
$cnt ++; 
} 

//Now it's grouped by date 

阵列输出:

array(5) 
{ 
     ["02"]=> array(2) 
       { 
        [0]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" } 
        [1]=> array(2) { [0]=> string(2) "30" [1]=> string(9) "the co op" } 
       } 
     ["03"]=> array(1) 
       { 
        [2]=> array(2) { [0]=> string(2) "50" [1]=> string(9) "the co op" } 
       } 
     ["04"]=> array(1) 
       { 
        [3]=> array(2) {[0]=> string(2) "40" [1]=> string(9) "the co op" } 
       } 
     ["05"]=> array(2) 
       { 
        [4]=> array(2) {[0]=> string(2) "10" [1]=> string(9) "the co op" } 
        [5]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" } 
       } 
     ["06"]=> array(1) 
       { 
        [6]=> array(2) { [0]=> string(2) "10" [1]=> string(9) "the co op" } 
       } 
} 

数组密钥索引值不应该是,例如,[ '02'],但是,作为第一含阵列中,[0],像正常一样;和'03'应该是[1]。

我查了很多,的确帮助了我生成的代码,但是所有的答案似乎都是在更改大型数组内部的键值。我是新的多维数组,顺便说一句。提前致谢。

如果你想知道为什么我这样做,到目前为止,这是因为每个第一个数组应该对应不同的月份;这就是为什么我按日期和所有这些命令。

+0

'$ graph = array_values($ graph);' – jeroen

+0

_and'03'should be [1] ._ is not clear。你是否希望值“03”作为每个数组的一部分,包含数量和数量? –

+0

不,03对应于第一行子行,而不是子子阵列,即数量和位置。 – user1849962

回答

1

如果我有你的权利,你可以使用:array_values

$graph = array_values($graph); 

所以 “02” 将是0, “03” 将是1,...等等

+0

是的,我没有意识到这很容易;非常感谢;就是这样。我认为这将涉及foreach循环和一切大声笑。欢呼声 – user1849962

+0

任何想法如何我可以使子子数组键0,1等目前这是第一阵列;但是第二个子数组是2,第三个子数组是3等 – user1849962

+0

从$ graph的索引中删除$ cnt,所以设置行将是:'$ graph [$ month] [] = array(...' – Hossam

0

在$关键您的foreach将是该行在查询中出现的相对记录号。

$graph = array(); 
$cnt = 0; 
foreach($dbarray as $key => $values){ 
    $orderdate = explode('-', $values['duedate']); 
    $month = $orderdate[1]; 
    $graph[$month][$cnt] = array (
    $graph[$key] = array (
     $month, 
     $values['amount'], 
     $values['towhich'] 
    ); 
    $cnt ++; 
} 
相关问题