Welcome Guest, Not a member yet? Register   Sign In
Query Multi-Dimensional Array and append value
#1

[eluser]jtotheb[/eluser]
I have a 2 dimensional array that i need to check for a value (the value is in a normal array and i want to do something like
Code:
if in_array
and if that value is present then add another value to the array.

The below is the code i have:

Code:
$multi = Array(array(
                'BAND' => '1',
                'VALUE' => 'Test',
                'parent' => '99999999'
                
                
),
array(
                'BAND' => '2',
                'VALUE' => 'Test2',
                'parent' => '99999999'
                
                
),
array(
                'BAND' => '3',
                'VALUE' => 'Test3',
                'parent' => '99999999'
                
                
),

array(
                'BAND' => '4',
                'VALUE' => 'Test3',
                'parent' => '99999999'
                                
                
                
)

);

$numbers = array(
                    '1',
                    '2',
                    '3'
                

);

And i want to say something like: if in_array($value, $numbers) add array item so that the array above now looks like this:

Code:
$multi = Array(array(
                'BAND' => '1',
                'VALUE' => 'Test',
                'parent' => '99999999',
                'new_value' => '1'
                
                
),
array(
                'BAND' => '2',
                'VALUE' => 'Test2',
                'parent' => '99999999',
                'new_value' => '1'
                
                
),
array(
                'BAND' => '3',
                'VALUE' => 'Test3',
                'parent' => '99999999',
                'new_value' => '1'
                
                
),

array(
                'BAND' => '4',
                'VALUE' => 'Test3',
                'parent' => '99999999',
                                
                
                
)

);

I hope this makes sense to someone and i hope someone can help!!

Cheers!!
#2

[eluser]davidbehler[/eluser]
Code:
foreach($multi as $key => $value)
{
   if(in_array($value['BAND'], $numbers)
   {
     $multi[$key]['new_value'] = 1;
   }
}

untested but might actually work.
#3

[eluser]jtotheb[/eluser]
Hey that works great!! Thank you!!

What if i had another sub array, how would i do the same above for a lower level of array?

Thanks again waldmeister, i don't use multi-dimensional arrays very often so have been finding this hard.
#4

[eluser]davidbehler[/eluser]
you would need nested foreach loops:
Code:
foreach($multi as $key => $value)
{
   foreach($value as $sub_key => $sub_value)
   {
      if(in_array($sub_value['BAND'], $numbers)
      {
        $multi[$key][$sub_key]['new_value'] = 1;
      }
   }
}
#5

[eluser]jtotheb[/eluser]
Ah okay, cool cheers!




Theme © iAndrew 2016 - Forum software by © MyBB