Reputation: 25
In order to import database data with ease, I have tried to write some php code in order to help me out. I have 2 arrays, "list" wich is regular aray. Other "order1" is an associative array. I'm trying to compare value of first with keys of second to make list that I need.. Something like multi find and replace..
array: list
[0] => Apple
[1] => Apple
[2] => Apple
[3] => Apple
[4] => Bannana
[5] => Mango
[6] => Mango
[7] => Mango
[8] => Mango
[9] => Mango
[10] => Pear
[11] => Pear
[12] => Pear
[13] => Pear
[14] => Pineaple
[15] => Strawberry
[16] => Strawberry
[17] => Watermelon
[18] => Watermelon
[19] => Watermelon
[20] => Watermelon
array: order1
[Apple] => 1
[Bannana] => 2
[Mango] => 3
[Pear] => 4
[Pineaple] => 5
[Strawberry] => 6
[Watermelon] => 7
I want to get:
1
1
1
1
2
3
3
3
3
3
4
4
4
4
5
6
6
7
7
7
7
But..
$final=array();
foreach($list as $keyl => $valuel){
foreach($order1 as $keyo => $valueo){
if($valuel==$keyo) {
$final[].=$valueo;
}
}
}
print_r($final);
gets me just 7, last element..
Something wrong with recursion/life of var? But I can't seem to get it..
Upvotes: 2
Views: 126
Reputation: 38416
Since the part you're interested in is the "value" of $order1
which has indexes you'll know, you won't need the inner-loop and instead you can just use isset()
to verify that the index exists and, if so, reference it directly.
For instance:
$final = array();
foreach ($list as $index => $key_name) {
if (isset($order1[$key_name])) {
$final[] = $order1[$key_name];
}
}
print_r($final);
Upvotes: 3
Reputation: 319
I think you messed up in your array initialization as the following code work as you expect (from what I understand)
$list = ["Apple", "Apple", "Apple", "Apple", "Bannana", "Mango", "Mango", "Mango", "Mango", "Mango", "Pear", "Pear", "Pear", "Pear", "Pineaple", "Strawberry", "Strawberry", "Watermelon", "Watermelon", "Watermelon", "Watermelon"];
$order1 = [
"Apple" => 1,
"Bannana" => 2,
"Mango" => 3,
"Pear" => 4,
"Pineaple" => 5,
"Strawberry" => 6,
"Watermelon" => 7
];
$final=array();
foreach($list as $keyl => $valuel){
foreach($order1 as $keyo => $valueo){
if($valuel==$keyo) {
$final[].=$valueo;
}
}
}
print_r($final)
Upvotes: 2