在多维数组的中间插入数组

时间:2016-12-08 14:51:22

标签: php

我试图在我的多维数组中插入一个数组,在代码的第一个sql部分它工作正常,但是当我使用array_splice它似乎不明白我试图插入整个数组并只是提出其他东西。 谁能帮助我得到正确答案?

这是我试图获得的结果:

Array
(
[0] => Array
    (
        [0] => 1
        [1] => företag1
    )
[1] => Array
    (
        [0] => 3
        [1] => subföretag1
    )

[2] => Array
    (
        [0] => 5
        [1] => subföretag2
    )

[3] => Array
    (
        [0] => 6
        [1] => subföretag3
    )

[4] => Array
    (
        [0] => 2
        [1] => företag2
    )

[5] => Array
    (
        [0] => 4
        [1] => företag3
    )
)

这就是我得到的:

Array
(
[0] => Array
    (
        [0] => 1
        [1] => företag1
    )

[1] => 3
[2] => 6
[3] => subföretag3
[4] => 5
[5] => subföretag2
[6] => subföretag1
[7] => Array
    (
        [0] => 2
        [1] => företag2
    )

[8] => Array
    (
        [0] => 4
        [1] => företag3
    )

)

这是使用的数组:

$partarray=array($row['id'],$row['name']);
in the first part: $partarray=array(random number from db,random name);
in the second part: $partarray=array(random number from db,random name);

这是我目前使用的代码:

$departments = array();
$sth = $pdo->prepare('SELECT id, name FROM departments WHERE companyid = 1 AND subgroupof = 0');
$sth->execute(); //executes the array
while($row = $sth->fetch()){
    $partarray=array($row['id'],$row['name']);
    array_push($departments, $partarray);
}
$sth = $pdo->prepare('SELECT * FROM departments WHERE companyid = 1 AND subgroupof != 0'); 
$sth->execute(); //executes the array
while($row = $sth->fetch()){
      $partarray=array($row['id'],$row['name']);
      array_splice($departments, $row['subgroupof'], 0, $partarray);
}
print("<pre>".print_r($departments,true)."</pre>");

1 个答案:

答案 0 :(得分:1)

试试这个。

$departments = array();
$sth = $pdo->prepare('SELECT id, name FROM departments WHERE companyid = 1 AND subgroupof = 0');
$sth->execute(); //executes the array

while($row = $sth->fetch()){
    $departments[] = array($row['id'], $row['name']);

    $sub_sth = $pdo->prepare(
        "SELECT id, name FROM departments WHERE companyid = 1 AND subgroupof = {$row['id']}"
    );

    $sub_sth->execute(); //executes the array
    while($sub_row = $sub_sth->fetch()) {
          $departments[] = array($sub_row['id'], $sub_row['name']);
    }
}

print("<pre>".print_r($departments,true)."</pre>");