what happens with my array? items disappear - php

what happens with my result array here? i expected the size of the result array to be equal to the input array, but its missing 3 entries.. where did they go? they didn't go to $ret , as they were supposed to..
code:
<?php
init();
$list_xy = array(
0 => array(
'id' => '308',
'x' => '37',
'y' => '63'
),
1 => array(
'id' => '963',
'x' => '38',
'y' => '134'
),
2 => array(
'id' => '385',
'x' => '39',
'y' => '132'
),
3 => array(
'id' => '1231',
'x' => '50',
'y' => '199'
),
4 => array(
'id' => '788',
'x' => '51',
'y' => '59'
),
5 => array(
'id' => '1151',
'x' => '53',
'y' => '61'
),
6 => array(
'id' => '671',
'x' => '55',
'y' => '60'
),
7 => array(
'id' => '1487',
'x' => '55',
'y' => '55'
)
);
$sorted_list_xy = sort_by_xy_distance($list_xy);
$sorted_list_xy_size = count($sorted_list_xy, COUNT_NORMAL);
$list_xy_size = count($list_xy, COUNT_NORMAL);
var_dump($sorted_list_xy_size == $list_xy_size ? "looks right" : "something is wrong", $sorted_list_xy_size, $list_xy_size);
die("died");
function sort_by_xy_distance($input_list)
{
$ret = array();
$a = $input_list[0];
array_push($ret, $input_list[0]);
$input_list[0] = null;
$i = 1;
for ($i = 1; $i < count($input_list); ++$i) {
if ($input_list[$i] == null) {
echo 'already added to list..';
continue;
}
$ii = 1;
$tmpdistance = 0;
$nearest = array(
'index' => -1,
'distance' => PHP_INT_MAX
);
for ($ii = 1; $ii < count($input_list); ++$ii) {
if ($input_list[$ii] == null || $ii == $i) {
//echo 'already added to list..';
continue;
}
$tmpdistance = abs($input_list[$ii]['x'] - $a['x']) + abs($input_list[$ii]['y'] - $a['y']);
if ($tmpdistance < $nearest['distance']) {
$nearest['index'] = $ii;
$nearest['distance'] = $tmpdistance;
}
}
assert($nearest['index'] != -1);
array_push($ret, $input_list[$nearest['index']]);
$a = $input_list[$nearest['index']];
$input_list[$nearest['index']] = null;
}
return $ret;
}
function init()
{
error_reporting(E_ALL);
set_error_handler("exception_error_handler");
}
function exception_error_handler($errno, $errstr, $errfile, $errline)
{
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting
return;
}
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
output:
already added to list..already added to list..already added to
list..string(18) "something is wrong" int(5) int(8) died
expected output: (something similar to)
already added to list..already added to list..already added to
list..string(11) "looks right" int(8) int(8) died
what i expected the list to turn in to:
a list where the difference to the next's [x][y] is as little as possible, which would be:
array(8) {
[0]=>
array(3) {
["id"]=>
string(3) "308"
["x"]=>
string(2) "37"
["y"]=>
string(2) "63"
}
[1]=>
array(3) {
["id"]=>
string(3) "788"
["x"]=>
string(2) "51"
["y"]=>
string(2) "59"
}
[2]=>
array(3) {
["id"]=>
string(4) "1151"
["x"]=>
string(2) "53"
["y"]=>
string(2) "61"
}
[3]=>
array(3) {
["id"]=>
string(3) "671"
["x"]=>
string(2) "55"
["y"]=>
string(2) "60"
}
[4]=>
array(3) {
["id"]=>
string(4) "1487"
["x"]=>
string(2) "55"
["y"]=>
string(2) "55"
}
[5]=>
array(3) {
["id"]=>
string(3) "385"
["x"]=>
string(2) "39"
["y"]=>
string(3) "132"
}
[6]=>
array(3) {
["id"]=>
string(3) "963"
["x"]=>
string(2) "38"
["y"]=>
string(3) "134"
}
[7]=>
array(3) {
["id"]=>
string(4) "1231"
["x"]=>
string(2) "50"
["y"]=>
string(3) "199"
}
}
I suck at making graphical illustrations, but ill give it a go.
This is my map:
map http://imagizer.imageshack.us/a/img633/3521/E0HGRe.png
i need to visit all the black dots.
This is my current path:
this path is not very optimal..
here is the path i want:
and that's what the sort function is trying to find, the shortest path to visit all the black dots.

Distance calculation you should use Pythagoras' theorem (or just hypot, like #prodigitalson mentioned). For geo coordinates you could use this: http://www.movable-type.co.uk/scripts/latlong.html
Let's fix your code. Every step of your first loop should take one value from input value and place it into result. But it has continue inside, therefor some steps of first loop do not do their job. Try to remove first continue.
$list_xy = array(
0 => array(
'id' => '308',
'x' => '37',
'y' => '63'
),
1 => array(
'id' => '963',
'x' => '38',
'y' => '134'
),
2 => array(
'id' => '385',
'x' => '39',
'y' => '132'
),
3 => array(
'id' => '1231',
'x' => '50',
'y' => '199'
),
4 => array(
'id' => '788',
'x' => '51',
'y' => '59'
),
5 => array(
'id' => '1151',
'x' => '53',
'y' => '61'
),
6 => array(
'id' => '671',
'x' => '55',
'y' => '60'
),
7 => array(
'id' => '1487',
'x' => '55',
'y' => '55'
)
);
$sorted_list_xy = sort_by_xy_distance($list_xy);
$sorted_list_xy_size = count($sorted_list_xy, COUNT_NORMAL);
$list_xy_size = count($list_xy, COUNT_NORMAL);
var_dump($sorted_list_xy_size == $list_xy_size ? "looks right" : "something is wrong", $sorted_list_xy_size, $list_xy_size);
die("died");
function sort_by_xy_distance($input_list)
{
$ret = array();
$a = $input_list[0];
array_push($ret, $input_list[0]);
$input_list[0] = null;
$i = 1;
for ($i = 1; $i < count($input_list); ++$i) {
// up here
// if ($input_list[$i] == null) {
// echo 'already added to list..';
// continue;
// }
$ii = 1;
$tmpdistance = 0;
$nearest = array(
'index' => -1,
'distance' => PHP_INT_MAX
);
for ($ii = 1; $ii < count($input_list); ++$ii) {
if ($input_list[$ii] == null || $ii == $i) {
//echo 'already added to list..';
continue;
}
$tmpdistance = abs($input_list[$ii]['x'] - $a['x']) + abs($input_list[$ii]['y'] - $a['y']);
if ($tmpdistance < $nearest['distance']) {
$nearest['index'] = $ii;
$nearest['distance'] = $tmpdistance;
}
}
assert($nearest['index'] != -1);
array_push($ret, $input_list[$nearest['index']]);
$a = $input_list[$nearest['index']];
$input_list[$nearest['index']] = null;
}
return $ret;
}

Related

How to remove specific number of elements from array

I have a function, which delete elements from array:
function remove_from_cart($prod_name,$price,$params,$count)
{
$cart = array(
"0" => array (
'name' => 'Bolognese - Small (26cm)',
'params' => '',
'price' => '12'),
"1" => array (
'name' => 'Bolognese - Small (26cm)',
'params' => '',
'price' => '12')
);
$prod_arr = array(
"name"=> $prod_name,
"params"=> $params,
"price" => $price);
$count = count( array_keys( $cart, $prod_arr ));
while(($key = array_search($prod_arr, $cart)) !== false) {unset($cart[$key]);}
return array('cart' => $cart, 'count' => $count);
}
$rem = remove_from_cart('Bolognese - Small (26cm)', '12', $params, 1);
//here is i want to remove just 1 of 2 elements
How to modify this function to have ability to set number of elements which i want to delete from array?
Thank you!
Your example and question is not quite clear, but you can check this solution:
<?php
function remove_from_cart($prod_name,$price,$params,$count)
{
$cart = array(
"0" => array (
'name' => 'Bolognese - Small (26cm)',
'params' => '',
'price' => '12'),
"1" => array (
'name' => 'Bolognese - Small (26cm)',
'params' => '',
'price' => '12'),
"2" => array (
'name' => 'Bolognese - Small (26cm)',
'params' => '',
'price' => '12')
);
$prod_arr = array(
"name"=> $prod_name,
"params"=> $params,
"price" => $price);
$i = 0;
while(($key = array_search($prod_arr, $cart)) !== false && $i < $count) {unset($cart[$key]); $i++;}
return array('cart' => $cart, 'count' => $count);
}
$params = '';
$rem = remove_from_cart('Bolognese - Small (26cm)', '12', $params, 1);
var_dump($rem);
This would return two elements, because they are 3 elements and you pass 1 for $count if you pass 2, it would return 1 element:
Result for $rem = remove_from_cart('Bolognese - Small (26cm)', '12', $params, 1); :
array(2) { ["cart"]=> array(2) { [1]=> array(3) { ["name"]=> string(24) "Bolognese - Small (26cm)" ["params"]=> string(0) "" ["price"]=> string(2) "12" } [2]=> array(3) { ["name"]=> string(24) "Bolognese - Small (26cm)" ["params"]=> string(0) "" ["price"]=> string(2) "12" } } ["count"]=> int(1) }
Result for $rem = remove_from_cart('Bolognese - Small (26cm)', '12', $params, 2); :
array(2) { ["cart"]=> array(1) { [2]=> array(3) { ["name"]=> string(24) "Bolognese - Small (26cm)" ["params"]=> string(0) "" ["price"]=> string(2) "12" } } ["count"]=> int(2) }

How to build a multidimensional array tree from an associative array in PHP?

I'm trying to build a multidimensional array tree from an associative array by replacing the 's' and 'd' key string values with their respective key 'bandnumber' arrays but can't seem to crack it. I've only been able to make it work for the first node of the array.
For example, I have the following array:
$coiArray = array (
array('bandnumber' => '02-BELG-2129929', 's' =>'94-BELG-3237180', 'd' => '96-BELG-3156295' ),
array('bandnumber' => '94-BELG-3237180', 's' =>'88-BELG-3206112', 'd' => '88-BELG-3206173' ),
array('bandnumber' => '88-BELG-3206112', 's' =>'81-BELG-3238253', 'd' => '87-BELG-3008002' ),
array('bandnumber' => '88-BELG-3206173', 's' =>'', 'd' => '' ),
array('bandnumber' => '96-BELG-3156295', 's' =>'88-BELG-3206112', 'd' => '85-BELG-3049648' ),
array('bandnumber' => '85-BELG-3049648', 's' =>'', 'd' => '' ),
array('bandnumber' => '81-BELG-3238253', 's' =>'', 'd' => '' ),
array('bandnumber' => '87-BELG-3008002', 's' =>'', 'd' => '' ),
);
And I'm trying to programmatically convert the above array into the following multidimensional array tree:
$coiNestedArray = array('bandnumber' => '02-BELG-2129929',
's' => array('bandnumber' => '94-BELG-3237180',
's' => array('bandnumber' => '88-BELG-3206112',
's' => array('bandnumber' => '81-BELG-3238253',
's' =>'',
'd' => ''
),
'd' => array('bandnumber' => '87-BELG-3008002',
's' =>'',
'd' => ''
)
),
'd' => array('bandnumber' => '88-BELG-3206173',
's' =>'',
'd' => ''
)
),
'd' => array('bandnumber' => '96-BELG-3156295',
's' => array('bandnumber' => '88-BELG-3206112',
's' => array('bandnumber' => '81-BELG-3238253',
's' =>'',
'd' => ''
),
'd' => array('bandnumber' => '87-BELG-3008002',
's' =>'',
'd' => ''
)
),
'd' => array('bandnumber' => '85-BELG-3049648',
's' =>'',
'd' => ''
)
)
);
This is the closest I've come thus far, but it only updates the first node of the array:
function findKey($coiarray, $bandnumber){
$thisCol = array_column($coiarray, 'bandnumber');
$found_key = array_search($bandnumber, $thisCol);
return $found_key;
}
foreach ($coiArray as $key => $value) {
$s = '';
$found_key = findKey($coiArray,$coiArray[$key]['s']);
if(isset($coiArray[$found_key])){
$s = $coiArray[$found_key];
}
$d = '';
$found_key = findKey($coiArray,$coiArray[$key]['d']);
if(isset($coiArray[$found_key])) {
$d = $coiArray[$found_key];
}
$coiArray[$key] = array('bandnumber' => $coiArray[$key]['bandnumber'], 's' => $s, 'd' => $d );
}
I will re-frame from posting the entire dump of the array here, but this is the first node of the $coiArray, from var_dump($coiArray), and you will notice all of the innermost nested ["s"] and ["d"] keys are strings instead of their respective arrays.
[0]=>
array(3) {
["bandnumber"]=>
string(15) "02-BELG-2129929"
["s"]=>
array(3) {
["bandnumber"]=>
string(15) "94-BELG-3237180"
["s"]=>
string(15) "88-BELG-3206112"
["d"]=>
string(15) "88-BELG-3206173"
}
["d"]=>
array(3) {
["bandnumber"]=>
string(15) "96-BELG-3156295"
["s"]=>
string(15) "88-BELG-3206112"
["d"]=>
string(15) "85-BELG-3049648"
}
}
The example below is the first node from the $coiNestedArray, which I created manually, to illustrate what I'm trying to achieve. Notice that every ["s"] and ["d"] is an array, derived from $coiArray.
array(3) {
["bandnumber"]=>
string(15) "02-BELG-2129929"
["s"]=>
array(3) {
["bandnumber"]=>
string(15) "94-BELG-3237180"
["s"]=>
array(3) {
["bandnumber"]=>
string(15) "88-BELG-3206112"
["s"]=>
array(3) {
["bandnumber"]=>
string(15) "81-BELG-3238253"
["s"]=>
string(0) ""
["d"]=>
string(0) ""
}
["d"]=>
array(3) {
["bandnumber"]=>
string(15) "87-BELG-3008002"
["s"]=>
string(0) ""
["d"]=>
string(0) ""
}
}
["d"]=>
array(3) {
["bandnumber"]=>
string(15) "88-BELG-3206173"
["s"]=>
string(0) ""
["d"]=>
string(0) ""
}
}
How do I solve this problem?
You would need to create an associative array keyed by bandnumbers, so you can directly find the row by bandnumbers. Then visit the children and replace each child with the corresponding value in that associative array, by reference.
Optionally detect which bandnumber was not referenced ever as a child: it is the root. But if you know the root bandnumber, or you know it is always the one in the first input row, then you can skip that last step. Finally extract the value of that root (assuming there is exactly one):
// Key the rows by their bandnumber:
foreach($coiArray as $row) {
$hash[$row["bandnumber"]] = $row;
}
foreach($hash as &$row) {
// Replace children with the corresponding row in the hash
foreach(["s","d"] as $prop) {
$child = $row[$prop];
if (!isset($hash[$child])) continue;
$row[$prop] =& $hash[$child];
$children[] = $child; // Keep track of non-root bandnumbers
}
}
// Only needed when you don't know which bandnumber is the root:
$root = current(array_diff(array_keys($hash), $children, ["s","d"]));
$result = $hash[$root];

Sorting a Multi-Dimensional Array by sum of object values in PHP

I have the below multi dimensional array of products. Each array is a pair of products that make a product set, I need to order the multi dimensional array by the total price of each product set.
array(4) {
[0]=>
array(2) {
["product1"]=>
object(stdClass)#5075 (2) {
["product_id"]=>
string(4) "9416"
["price"]=>
string(6) "110.00"
}
["product2"]=>
object(stdClass)#5077 (2) {
["product_id"]=>
string(4) "9431"
["price"]=>
string(6) "100.00"
}
}
[1]=>
array(2) {
["product1"]=>
object(stdClass)#5065 (2) {
["product_id"]=>
string(4) "1254"
["price"]=>
string(6) "75.00"
}
["product2"]=>
object(stdClass)#5067 (2) {
["product_id"]=>
string(4) "9431"
["price"]=>
string(6) "62.00"
}
}
[2]=>
array(2) {
["product1"]=>
object(stdClass)#5055 (2) {
["product_id"]=>
string(4) "9416"
["price"]=>
string(6) "45.00"
}
["product2"]=>
object(stdClass)#5057 (2) {
["product_id"]=>
string(4) "9431"
["price"]=>
string(6) "50.00"
}
}
[3]=>
array(2) {
["product1"]=>
object(stdClass)#5045 (2) {
["product_id"]=>
string(4) "9416"
["price"]=>
string(6) "60.00"
}
["product2"]=>
object(stdClass)#5047 (2) {
["product_id"]=>
string(4) "9431"
["price"]=>
string(6) "25.00"
}
}
}
I need to sort the multi-dimensional array by the total sum of product1 + product2 in each array in ascending order. For example [1] should be above [0] as 75+62 is less than 110 +100.
If anyone can help me with this it would be greatly appreciated.
You can use usort() for this purpose:-
function comparePrice($a,$b)
{
$a_price = $a['product1']->price + $a['product2']->price;
$b_price = $b['product1']->price + $b['product2']->price;
if ($a_price ==$b_price) return 0;
return ($a_price<$b_price)? -1:1;
}
usort($array,'comparePrice');
A hardcoded working example:- https://3v4l.org/mTfu6
You need to use user-defined sorting
http://php.net/manual/en/function.usort.php
usort($products, function($a, $b) {
$prodA = $a['product1']['price'] + $a['product2']['price'];
$prodB = $b['product1']['price'] + $b['product2']['price'];
if($prodA == $prodB) return 0;
return ($prodA < $prodB) ? -1 : 1;
});
The php7+ "spaceship operator" (aka three-way-comparison operator) makes the syntax with usort() as clean and brief as possible.
Code: (Demo)
$array = [
[
"product1" => (object) ["product_id" => "9416", "price"=>"110.00"],
"product2" => (object) ["product_id"=>"9431", "price"=>"100.00"]
],
[
"product1" => (object) ["product_id" => "1254", "price"=>"75.00"],
"product2" => (object) ["product_id"=>"9431", "price"=>"62.00"]
],
[
"product1" => (object) ["product_id" => "9416", "price"=>"45.00"],
"product2" => (object) ["product_id"=>"9431", "price"=>"50.00"]
],
[
"product1" => (object) ["product_id" => "9416", "price"=>"60.00"],
"product2" => (object) ["product_id"=>"9431", "price"=>"25.00"]
]
];
usort($array, function($a, $b) {
return $a['product1']->price + $a['product2']->price <=> $b['product1']->price + $b['product2']->price;
});
var_export($array);
Output:
array (
0 => // sum = 85.00
array (
'product1' =>
(object) array(
'product_id' => '9416',
'price' => '60.00',
),
'product2' =>
(object) array(
'product_id' => '9431',
'price' => '25.00',
),
),
1 => // sum = 95.00
array (
'product1' =>
(object) array(
'product_id' => '9416',
'price' => '45.00',
),
'product2' =>
(object) array(
'product_id' => '9431',
'price' => '50.00',
),
),
2 => // sum = 137.00
array (
'product1' =>
(object) array(
'product_id' => '1254',
'price' => '75.00',
),
'product2' =>
(object) array(
'product_id' => '9431',
'price' => '62.00',
),
),
3 => // sum = 210.00
array (
'product1' =>
(object) array(
'product_id' => '9416',
'price' => '110.00',
),
'product2' =>
(object) array(
'product_id' => '9431',
'price' => '100.00',
),
),
)

Sort Multidimensional Array By Searched Word

I need to sort a multidimensional array by a searched keyword.
My array is like below.
<?php
array(
array(
'name' => '11th-Physics',
'branch' => 'Plus One',
'college' => 'Plus One',
),
array(
'name' => 'JEE-IIT',
'branch' => 'Physics',
'college' => 'IIT College',
),
array(
'name' => 'Physics',
'branch' => 'Bsc Physics',
'college' => 'College of Chemistry',
),
array(
'name' => 'Chemical Engineering',
'branch' => 'Civil',
'college' => 'Physics Training Center',
),
array(
'name' => 'Physics Education',
'branch' => 'Mechanical',
'college' => 'TBR',
),
)
?>
I need to sort this array when search keyword is physics . And after Sorting i need the result like below.
NEEDED RESULT
<?php
array(
array(
'name' => 'Physics',
'branch' => 'Bsc Physics',
'college' => 'College of Chemistry',
),
array(
'name' => 'Physics Education',
'branch' => 'Mechanical',
'college' => 'TBR',
),
array(
'name' => '11th-Physics',
'branch' => 'Plus One',
'college' => 'Plus One',
),
array(
'name' => 'JEE-IIT',
'branch' => 'Physics',
'college' => 'IIT College',
),
array(
'name' => 'Chemical Engineering',
'branch' => 'Civil',
'college' => 'Physics Training Center',
),
)
?>
That is I need to sort the array first by the name which is exactly like the searched keyword. Then wildcard search in name. Then to the next key branch and same as above. Is there any php function to sort this array like my requirement. I have already checked asort, usort. But I didn't get result properly.
Just call this simple function I just created for your requirement, It works just fine :) change the priority order according to your need
function sortArray($array,$itemToSearch)
{
$sortedArray = array();
$priorityOrder = ['name','branch','college'];
foreach ($priorityOrder as $key)
{
foreach ($array as $i => $value)
{
if(strpos(strtolower($value[$key]), strtolower($itemToSearch)) === 0)
{
array_push($sortedArray, $value);
unset($array[$i]);
}
}
foreach ($array as $i => $value)
{
if(strpos(strtolower($value[$key]), strtolower($itemToSearch)) > 0)
{
array_push($sortedArray, $value);
unset($array[$i]);
}
}
}
return $sortedArray;
}
Here we go
So I started from the algorithm in this answer and modified it to fit your requirements. Since you have three different "priorities" to you sorting, we have to use some temporary variables to separate the elements we wish sorted.
// arrays used to separate each row based on the row where the word "Physics" is found
$searchName = array();
$searchBranch = array();
$searchCollege = array();
// arrays used later for array_multisort
$foundInName = array();
$foundInBranch = array();
$foundInCollege = array();
foreach ($var as $key => $row) {
if(strpos(strtolower($row['name']), 'physics') !== false) {
$searchName[$key] = $row['name'];
$foundInName[] = $row;
}
elseif(strpos(strtolower($row['branch']), 'physics') !== false) {
$searchBranch[$key] = $row['branch'];
$foundInBranch[] = $row;
}
elseif(strpos(strtolower($row['college']), 'physics') !== false) {
$searchCollege[$key] = $row['college'];
$foundInCollege[] = $row;
}
}
// Note: I use SORT_NATURAL here so that "11-XXXXX" comes after "2-XXXXX"
array_multisort($searchName, SORT_NATURAL, $foundInName); // sort the three arrays separately
array_multisort($searchBranch, SORT_NATURAL, $foundInBranch);
array_multisort($searchCollege, SORT_NATURAL, $foundInCollege);
$sortedArray = array_merge($foundInName, $foundInBranch, $foundInCollege);
Outputting $sortedArray using var_dump() gives something like:
array(5) {
[0]=> array(3) {
["name"]=> string(12) "11th-Physics"
["branch"]=> string(8) "Plus One"
["college"]=> string(8) "Plus One"
}
[1]=> array(3) {
["name"]=> string(7) "Physics"
["branch"]=> string(11) "Bsc Physics"
["college"]=> string(20) "College of Chemistry"
}
[2]=> array(3) {
["name"]=> string(17) "Physics Education"
["branch"]=> string(10) "Mechanical"
["college"]=> string(3) "TBR"
}
[3]=> array(3) {
["name"]=> string(7) "JEE-IIT"
["branch"]=> string(7) "Physics"
["college"]=> string(11) "IIT College"
}
[4]=> array(3) {
["name"]=> string(20) "Chemical Engineering"
["branch"]=> string(5) "Civil"
["college"]=> string(23) "Physics Training Center"
}
}
As you can see 11th-Physics comes out first. That is because the ASCII value of numbers is lower than that of letters. To fix this, modify the $search... arrays by prepending a high ASCII character before the string.
if(strpos(strtolower($row['name']), 'physics') !== false) {
// if the first character is a number, prepend an underscore
$searchName[$key] = is_numeric(substr($row['name'], 0, 1)) ? '_'.$row['name'] : $row['name'];
$foundInName[] = $row;
}
Which yields the following output:
array(5) {
[0]=> array(3) {
["name"]=> string(7) "Physics"
["branch"]=> string(11) "Bsc Physics"
["college"]=> string(20) "College of Chemistry"
}
[1]=> array(3) {
["name"]=> string(17) "Physics Education"
["branch"]=> string(10) "Mechanical"
["college"]=> string(3) "TBR"
}
[2]=> array(3) {
["name"]=> string(12) "11th-Physics"
["branch"]=> string(8) "Plus One"
["college"]=> string(8) "Plus One"
}
[3]=> array(3) {
["name"]=> string(7) "JEE-IIT"
["branch"]=> string(7) "Physics"
["college"]=> string(11) "IIT College"
}
[4]=> array(3) {
["name"]=> string(20) "Chemical Engineering"
["branch"]=> string(5) "Civil"
["college"]=> string(23) "Physics Training Center"
}
}
Try it here!

Recursion with multidimensional array

I have been working on this for long and I got it working as I want but I think there is simpler solution.
So far I got this:
$menu = array(
0 => (object) array(
'cat_id' => 1,
'cat_parent' => 0,
'cat_name' => 'domov',
'cat_href' => 'domov',
'cat_subcategories' => array()
),
1 => (object) array(
'cat_id' => 2,
'cat_parent' => 0,
'cat_name' => 'clanky',
'cat_href' => 'clanky',
'cat_subcategories' => array(
0 => (object) array(
'cat_id' => 9,
'cat_parent' => 2,
'cat_name' => 'apple clanky',
'cat_href' => 'apple',
'cat_subcategories' => array(
0 => (object) array(
'cat_id' => 11,
'cat_parent' => 9,
'cat_name' => 'iphone clanky',
'cat_href' => 'iphone',
'cat_subcategories' => array()
),
1 => (object) array(
'cat_id' => 12,
'cat_parent' => 9,
'cat_name' => 'macbook clanky',
'cat_href' => 'macbook',
'cat_subcategories' => array()
)
)
),
1 => (object) array(
'cat_id' => 10,
'cat_parent' => 2,
'cat_name' => 'microsoft clanky',
'cat_href' => 'microsoft',
'cat_subcategories' => array()
),
)
),
2 => (object) array(
'cat_id' => 3,
'cat_parent' => 0,
'cat_name' => 'produkty',
'cat_href' => 'produkty',
'cat_subcategories' => array()
),
3 => (object) array(
'cat_id' => 4,
'cat_parent' => 0,
'cat_name' => 'vyrobcovia',
'cat_href' => 'vyrobcovia',
'cat_subcategories' =>
array(
0 => (object) array(
'cat_id' => 5,
'cat_parent' => 4,
'cat_name' => 'apple',
'cat_href' => 'apple',
'cat_subcategories' => array(
0 => (object) array(
'cat_id' => 7,
'cat_parent' => 5,
'cat_name' => 'iphone',
'cat_href' => 'iphone',
'cat_subcategories' => array()
),
1 => (object) array(
'cat_id' => 8,
'cat_parent' => 5,
'cat_name' => 'macbook',
'cat_href' => 'macbook',
'cat_subcategories' => array()
)
)
),
1 => (object) array(
'cat_id' => 6,
'cat_parent' => 4,
'cat_name' => 'microsoft',
'cat_href' => 'microsoft',
'cat_subcategories' => array()
),
)
),
);
function generate_menu($menu, $level = 1, $tmp_array = array())
{
foreach($menu as $key => $c)
{
$menu_item = get_menu_elements($c, $level);
$tmp_array = array_replace_recursive($tmp_array, $menu_item);
foreach($c->cat_subcategories as $_key => $_c)
{
$menu_item = get_menu_elements($_c, $level+1);
$tmp_array = array_replace_recursive($tmp_array, $menu_item);
foreach($_c->cat_subcategories as $__key => $__c)
{
$menu_item = get_menu_elements($__c, $level+2);
$tmp_array = array_replace_recursive($tmp_array, $menu_item);
}
}
}
return $tmp_array;
}
function get_menu_elements($c, $level = 1)
{
$level_var = "level_".($level);
$output = array(
$level_var => array()
);
$output[$level_var][$c->cat_id] = array(
'parent' => $c->cat_parent,
'html' => $c->cat_name
);
return $output;
}
In the end I should have multidimensional array with:
array(3) {
["level_1"]=>
array(4) {
[1]=>
array(2) {
["parent"]=>
int(0)
["html"]=>
string(5) "domov"
}
[2]=>
array(2) {
["parent"]=>
int(0)
["html"]=>
string(6) "clanky"
}
[3]=>
array(2) {
["parent"]=>
int(0)
["html"]=>
string(8) "produkty"
}
[4]=>
array(2) {
["parent"]=>
int(0)
["html"]=>
string(10) "vyrobcovia"
}
}
["level_2"]=>
array(4) {
[9]=>
array(2) {
["parent"]=>
int(2)
["html"]=>
string(12) "apple clanky"
}
[10]=>
array(2) {
["parent"]=>
int(2)
["html"]=>
string(16) "microsoft clanky"
}
[5]=>
array(2) {
["parent"]=>
int(4)
["html"]=>
string(5) "apple"
}
[6]=>
array(2) {
["parent"]=>
int(4)
["html"]=>
string(9) "microsoft"
}
}
["level_3"]=>
array(4) {
[11]=>
array(2) {
["parent"]=>
int(9)
["html"]=>
string(13) "iphone clanky"
}
[12]=>
array(2) {
["parent"]=>
int(9)
["html"]=>
string(14) "macbook clanky"
}
[7]=>
array(2) {
["parent"]=>
int(5)
["html"]=>
string(6) "iphone"
}
[8]=>
array(2) {
["parent"]=>
int(5)
["html"]=>
string(7) "macbook"
}
}
}
I want to print multi-level menu recursion. I got it working with this code but in function generate_menu I had to use 3 foreach loops for cat_subcategories. When I used recursion like this:
function generate_menu($menu, $level = 1, $tmp_array = array())
{
foreach($menu as $key => $c)
{
$menu_item = get_menu_elements($c, $level);
$tmp_array = array_replace_recursive($tmp_array, $menu_item);
if (!empty($c->cat_subcategories)) generate_menu($c->cat_subcategories, $level + 1, $tmp_array);
}
return $tmp_array;
}
i got only 'level_1' in output
The output which I am getting now is the same I want I just want to simplify the multiple foreach()
etc. Basicaly
level_1 - first loop of $menu
level_2 - loop of cat_subcategories
level_3 - loop of cat_subcategories for cat_subcategories item
You essentially need to perform a breadth-first traversal in your menu tree. For that I would suggest an iterative function instead of a recursive function, as the latter is more suitable for a depth-first traversal.
Here is the function:
function generate_menu($menu) {
$result = [];
$level = 1;
while (count($menu)) {
$queue = [];
$items = [];
foreach($menu as $cat) {
$items[$cat->cat_id] = [
"parent" => $cat->cat_parent,
"html" => $cat->cat_name
];
$queue = array_merge($queue, $cat->cat_subcategories);
}
$result["level_$level"] = $items;
$level++;
$menu = $queue;
}
return $result;
}
See it run on eval.in.
As this function traverses the top level of the tree, it collects all the children into $queue. Once the top level has been translated into the output (in the level_1 key), that queue will have all second level entries. This then is moved to $menu, and the process is repeated, but now with level_2. This continues until a level is reached where no more entries are found.
I've made some time ago this function. It could help you.
I've got an array where $arr[actual item][parental id]
function getChild($id, $result, $count) {
for( $i = 0; $i < sizeof($result); $i ++) {
if( $result[$i][2] == $id) {
getChild($result[$i][0], $result, $count + 1);
}
}
}
EDIT
In my case, where all the items in the one-dimensional array, but with the hierarchy of n-dimensional array depended on the parental id.
CODE TO PRINT MENU
This code will work for N-number of hierarchy
static function printAllCategoriesAsCheckbox($arr, $d=0){
$htmlString = "";
if (is_array($arr)){
foreach($arr as $category){
$htmlString = $htmlString . '<div><input style="margin-left: ' . 30*$d . 'px;" value="'.$category->id.'" class="category-input" type="checkbox" name="category_id[]">';
$htmlString = $htmlString . ' <label for="category_'.$category->id.'">' . $category->name . '</label></div>';
if (is_array($category['childs'])){
$htmlString = $htmlString . ItemCategory::printAllCategoriesAsCheckbox($category['childs'], $d+1);
}
}
}
return $htmlString;
}

Categories