Reputation: 2005
I'm programming in PHP and I've these arrays:
Category array:
$type = array("fruit","veggie","other");
Subcategory arrays:
$fruit=array("apple","orange");
$veggie=array("bean","pea");
$other=array("bread","cake");
I can get all the elements of the subcategories with:
$all_elements = array_merge($fruit,$veggie,$other);
But this expressions has the problem that if I've to create new categories I've to rewrite the expression.
I'd like to know how I can get an expression like next one to get the same result:
$all_elements = array_merge(SOMETHING($type));
Thanks in advance!!!!!
Upvotes: 1
Views: 568
Reputation: 1649
Take a look at compact:
compact — Create array containing variables and their values
So you want to do:
$type = array("fruit","veggie","other");
$fruit=array("apple","orange");
$veggie=array("bean","pea");
$other=array("bread","cake");
print_r(compact(($type)));
OUTPUT
Array
(
[fruit] => Array
(
[0] => apple
[1] => orange
)
[veggie] => Array
(
[0] => bean
[1] => pea
)
[other] => Array
(
[0] => bread
[1] => cake
)
)
However, I recommend you to do it completly differently, as @Rasclatt suggested:
$food['fruit'][] = 'apple';
$food['fruit'][] = 'orange';
$food['veggie'][] = 'bean';
$food['veggie'][] = 'pea';
$food['other'][] = 'bread';
$food['other'][] = 'cake';
Upvotes: 2
Reputation: 12505
I think I would create one array that you can add to. You can more easily merge and handle new categories. You can loop through the array to get types and sub-types.
$food['fruit'][] = 'apple';
$food['fruit'][] = 'orange';
$food['veggie'][] = 'bean';
$food['veggie'][] = 'pea';
$food['other'][] = 'bread';
$food['other'][] = 'cake';
Upvotes: 1
Reputation: 1527
I would layout the data differently:
$item["fruit"]=array("apple","orange");
$item["veggie"]=array("bean","pea");
$item["other"]=array("bread","cake");
So if you want $all_elements
you could just ask for $item
instead:
print_r ($item);
And if you want a certain category:
print_r ($item["veggie"]);
Upvotes: 0