Reputation: 151
im trying to insert an array into my multidimensional array, in the first sql part of the code it works fine, however when i use array_splice it doesnt seem to understand that im trying to insert the whole array and just puts up something else. could anyone help me to get the correct answer?
This is the result im trying to get:
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
)
)
and this is what i get:
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
)
)
this is the arrays im using:
$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);
this is the code im currently using:
$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>");
Upvotes: 0
Views: 135
Reputation: 999
Try this.
$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>");
Upvotes: 1