Homer_J
Homer_J

Reputation: 3323

PHP Multidimensional Array Search - where values not unique

I have the following array $outs:

Array ( 
    [0] => Array ( [Dept] => Sales      [Team] => Field    [Out_Count] => 14 ) 
    [1] => Array ( [Dept] => IT         [Team] => Tech Sup [Out_Count] => 2 ) 
    [2] => Array ( [Dept] => Marketing  [Team] => Digital  [Out_Count] => 33 ) 
    [3] => Array ( [Dept] => Operations [Team] => Field    [Out_Count] => 7 ) 
    [4] => Array ( [Dept] => Finance    [Team] => Corp     [Out_Count] => 7 ) 
)

I have a varaible as follows:

   $los = 'Field';

I have the following code that brings back the value of Out_Count as follows based on Team:

$key = array_search($los, array_column($outs, 'Team'));   
$count = $outs[$key]['Out_Count'];

However, I'm running into problems because Field isn't unique! I've tried the following...but no joy:

$los = 'Field';
$loc = 'Sales';

and then:

$key = array_search($loc, array_column($outs, 'Dept'), $los, array_column($outs, 'Team'));   
$count = $outs[$key]['Out_Count'];

But no joy...clearly I'm going wrong! Any advice would be helpful!

Upvotes: 2

Views: 72

Answers (1)

Rikesh
Rikesh

Reputation: 26451

You can try,

$search = ['Team' => 'Field', 'Dept' => 'Sales'];
$keys = array_keys(
    array_filter(
        $outs,
        function ($v) use ($search) { return $v['Team'] == $search['Team'] && $v['Dept'] == $search['Dept']; }
    )
);
$key = $keys[0];
$count = $outs[$key]['Out_Count'];

Upvotes: 1

Related Questions