0

I have 2 arrays, I want match this arrays and get results with keys. Can I search in first array with second array keys or match diffrent way?

$boardLists = [
  [
    '_id' => 'a1a1a1',
    'name' => 'Board Name #1',
    'code' => 'B1'
  ],
  [
    '_id' => 'b2b2b2',
    'name' => 'Board Name #2',
    'code' => 'B2
  ]
];

and

$boards = [
  'a1a1a1',
  'b2b2b2',
  'c3c3c3'
];

My result with array_intersect:

array(1) { [0]=> string(6) "a1a1a1" }

My expected result if match 'a1a1a1':

[
  '_id' => 'a1a1a1',
  'name' => 'Board Name #1',
  'code' => 'B1'
],
5
  • add what is your expected result. Commented Apr 26, 2018 at 16:08
  • @prasannaputtaswamy I added Commented Apr 26, 2018 at 16:13
  • basically you will have multi-dimentional array1 & another array1. you want compare that. return matching array with array2. is that correct Commented Apr 26, 2018 at 16:15
  • @prasannaputtaswamy Yes, exactly. Commented Apr 26, 2018 at 16:17
  • boards has two matching a1a1a1 & b1b1b1 whereas you mentioned only one in result Commented Apr 26, 2018 at 16:28

3 Answers 3

2

That I could understand you want to search in the first array according to what you have in the second array, so here is one example:

$boardLists = [
  [
    '_id' => 'a1a1a1',
    'name' => 'Board Name #1',
    'code' => 'B1'
  ],
    [
    '_id' => 'b2b2b2',
    'name' => 'Board Name #2',
    'code' => 'B2' 
  ]

];

$boards = [
  'a1a1a1',
  'b2b2b2',
  'c3c3c3'
];
$boardListIds = array_column($boardLists, '_id');

$results = [];
foreach ($boards as $board) {
  $find_key = array_search($board, $boardListIds);
  if($find_key !== false)
    $results[] = $find_key;
}

#printing the results
foreach ($results as $result) {
  print_r($boardLists[$result]);
}

There many ways to do it, this is just one. I hope it helps. :)

Sign up to request clarification or add additional context in comments.

Comments

1

It would be more efficient to have the array index of your first array the _id. However with the way the array is setup currently you could do:

foreach($boards as $key1=>board){
    foreach($boardLists as $key2=>$boardList){
        if($boardList['_id']==$key1){
                echo $key1 . PUP_EOL;
                print_r($boardList);
        }
    }
}

Comments

0

Try this

$finalArray = array();
foreach($boardLists  as $key=>$val):
    if(in_array($val['_id'],$boards))
    {
        $finalArray[] = $val2;
    }
endforeach;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.