Recursion with multidimensional array - php

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;
}

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) }

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',
),
),
)

Adding another dimension to array

I have an array of TLDs and prices, and now I want to be able to add a classification i.e. 'Australian','New Zealand','Industry' to the domains but I am having troubles adding the extra dimension.
The array I have is
$domains = array(
'.com.au' => '19.98',
'.melbourne' => '90.00',
'.academy' => '45.00',
'.accountants' => '120.00',
'.ac.nz' => '36.75');
$domains = array(
'.com.au' => array(
'country' => 'Australia',
'sector' => 'Industry',
'price' => '19.98'
),
);
Is this a beginning on what you're looking for ?
Is this code ok for you?
<?php
$domains = array(
'.com.au' => '19.98',
'.melbourne' => '90.00',
'.academy' => '45.00',
'.accountants' => '120.00',
'.ac.nz' => '36.75');
$newDomains = [];
foreach($domains as $key=>$value){
if($key == '.com.au'){
$newDomains[$key]['TLD'] = $value;
$newDomains[$key]['Industry'] = 'blabal';
}else{
$newDomains[$key] = $value;
}
}
echo '<pre>';
var_dump($newDomains);
echo '</pre>';
?>
Or even:
$domains = array(
'.com.au' => '19.98',
'.melbourne' => '90.00',
'.academy' => '45.00',
'.accountants' => '120.00',
'.ac.nz' => '36.75');
$industryArray = array(
'.com.au' => 'blabla'
);
$newDomains = [];
foreach($domains as $key=>$value){
if(isset($industryArray[$key])){
$newDomains[$key]['TLD'] = $value;
$newDomains[$key]['Industry'] = $industryArray[$key];
}else{
$newDomains[$key] = $value;
}
}
echo '<pre>';
var_dump($newDomains);
echo '</pre>';
The result is:
array(5) {
[".com.au"]=>
array(2) {
["TLD"]=>
string(5) "19.98"
["Industry"]=>
string(6) "blabla"
}
[".melbourne"]=>
string(5) "90.00"
[".academy"]=>
string(5) "45.00"
[".accountants"]=>
string(6) "120.00"
[".ac.nz"]=>
string(5) "36.75"
}

what happens with my array? items disappear

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;
}

Separating array rows into other arrays based on key name

I have an array like this
$rows = array(
array(
'fruit.name' => 'Apple',
'fruit.colour' => 'Red',
'fruit.weight' => '0.1',
'vegetable.name' => 'Carrot',
'vegetable.colour' => 'Orange',
'vegetable.weight' => '0.05'
),
array(
'fruit.name' => 'Banana',
'fruit.colour' => 'Yellow',
'fruit.weight' => '0.7',
'vegetable.name' => 'Potato',
'vegetable.colour' => 'Brown',
'vegetable.weight' => '0.6'
)
);
And i want to be able to sort the array into 2 other arrays called 'fruits' and 'vegetables' based on the first part of the key name so up to the decimal point. With this array I should have 2 rows in each of the fruits and vegetable arrays.
I have this code but it doesn't work and I can't see what I'm doing wrong.
$fruits = array();
$vegetables = array();
foreach($rows as $row)
{
foreach($row as $key => $value)
{
if('fruit' == substr($key, 0, strpos($key, '.')))
{
$fruits[$key] = $row;
}
else
{
$vegetables[$key] = $row;
}
}
}
echo "<pre>"; var_dump($fruits); echo "</pre>";
When i do a var_dump i get this
array(3) {
["fruit.name"]=>
array(6) {
["fruit.name"]=>
string(6) "Banana"
["fruit.colour"]=>
string(6) "Yellow"
["fruit.weight"]=>
string(3) "0.7"
["vegetable.name"]=>
string(6) "Potato"
["vegetable.colour"]=>
string(5) "Brown"
["vegetable.weight"]=>
string(3) "0.6"
}
["fruit.colour"]=>
array(6) {
["fruit.name"]=>
string(6) "Banana"
["fruit.colour"]=>
string(6) "Yellow"
["fruit.weight"]=>
string(3) "0.7"
["vegetable.name"]=>
string(6) "Potato"
["vegetable.colour"]=>
string(5) "Brown"
["vegetable.weight"]=>
string(3) "0.6"
}
["fruit.weight"]=>
array(6) {
["fruit.name"]=>
string(6) "Banana"
["fruit.colour"]=>
string(6) "Yellow"
["fruit.weight"]=>
string(3) "0.7"
["vegetable.name"]=>
string(6) "Potato"
["vegetable.colour"]=>
string(5) "Brown"
["vegetable.weight"]=>
string(3) "0.6"
}
}
Any help please getting this to separate the array into 2 arrays each containing either fruits or vegetables.
This seems to work:
$rows = array(
array(
'fruit.name' => 'Apple',
'fruit.colour' => 'Red',
'fruit.weight' => '0.1',
'vegetable.name' => 'Carrot',
'vegetable.colour' => 'Orange',
'vegetable.weight' => '0.05'
),
array(
'fruit.name' => 'Banana',
'fruit.colour' => 'Yellow',
'fruit.weight' => '0.7',
'vegetable.name' => 'Potato',
'vegetable.colour' => 'Brown',
'vegetable.weight' => '0.6'
)
);
$fruits = $vegs = array();
foreach ($rows as $arrays) {
$fruit = array();
$veg = array();
foreach ($arrays as $key => $val) {
$index = substr($key, strpos($key, ".") + 1);
if('fruit' == substr($key, 0, strpos($key, '.'))){
$fruit[$index] = $val;
} else {
$veg[$index] = $val;
}
}
$fruits[] = $fruit;
$vegs[] = $veg;
}
var_dump($fruits, $vegs);
(Please overlook the fact I've called one of the vars $vegs)
Hope this helps!
I didn't run the code, but it looks like you want:
$fruits[$key] = $value;
-AND-
$vegetables[$key] = $value;

Categories