Reputation: 875
so I am building a menu to a site, ant the menu will be populated by the database, when I query the database I get something like this array:
Array:
Array
(
[0] => Array
(
[id] => 1
[nome] => Home
[parent_id] => 0
)
[1] => Array
(
[id] => 2
[nome] => Tutorials
[parent_id] => 0
)
[2] => Array
(
[id] => 3
[nome] => Photoshop
[parent_id] => 2
)
[3] => Array
(
[id] => 4
[nome] => Illustrato
[parent_id] => 2
)
[4] => Array
(
[id] => 5
[nome] => Web Design
[parent_id] => 2
)
[5] => Array
(
[id] => 6
[nome] => HTML
[parent_id] => 5
)
[6] => Array
(
[id] => 7
[nome] => CSS
[parent_id] => 5
)
)
I would like to search it and get just the child items, for instance:
function getChild($needle){
...
return $array
}
where $array, is the information of the children:
print_r(getChild(2));
would output something like this:
Array ( [0] => 3 [1] => 4 [2] => 5 )
in this example it returns the ids but it could return an array with the complete info for each one of the items...
I could query the database again and obtain the same results but I'm afraid that it is not a good practice. For example if I have a gigantic menu, the script would be querying too much the database and that would slow down the rendering of the page too much.
I am tiered of searching a way of doing this I'm already dizzy and exhausted...
I realize that in this example I have no links but it is easy to add them in the end, that's why I don't work with them for now :P
Upvotes: 1
Views: 106
Reputation: 10469
It might look something like this (assuming I understand your issue properly):
function getChild( $needle, $sourceArray )
{
$ret = array();
for( $i = $needle; $i < $sourceArray.count(); $i++ )
{
array_push( $ret, $sourceArray[ $i ][ 'id ' ]) ;
}
return $ret;
}
EDITED: the function isn't length() - it's count()
Upvotes: 1
Reputation: 48599
You will need to pass your array into the function getChild():
getChild($data, 1, 2)
Something like this:
function getChild(){
$results = [];
$args = func_get_args();
$arrays = array_shift($args);
foreach ($arrays as $subarr) {
$curr_results = [];
$keys = array_keys($subarr);
foreach ($args as $index) {
$curr_results[] = $subarr[$keys[$index]];
}
$results[] = $curr_results;
}
return $results;
}
$data = [
["id" => 1, "nome" => "Home", "parent id" => 0],
["id" => 2, "nome" => "Tutorials", "parent id" => 0],
["id" => 3, "nome" => "Photoshop", "parent id" => 0],
["id" => 4, "nome" => "Illustrato", "parent id" => 2],
];
print_r(getChild($data, 1, 2));
--output:--
Array
(
[0] => Array
(
[0] => Home
[1] => 0
)
[1] => Array
(
[0] => Tutorials
[1] => 0
)
[2] => Array
(
[0] => Photoshop
[1] => 0
)
[3] => Array
(
[0] => Illustrato
[1] => 2
)
)
I have to say, that seems like a stupid way to obfuscate your code. It would be much clearer to write:
getChildData($data, "nome", "parent_id");
Instead, you are trying to access an associative array with numeric indexes.
Upvotes: 1