hpgodwin
hpgodwin

Reputation: 23

Combing matched keys in an array

Edited I get the combined item_ids now, but not the single item_ids.

I have an array with three keys.

$searchArray = { 
[0]=> array(3) {
      ["keyword"]=> string(7) "history" 
      ["url"]=> string(7) "history" 
      ["item_id"]=> string(2) "16" 
}  
[1]=> array(3) {
      ["keyword"]=> string(4) "past"
      ["url"]=> string(4) "past" 
      ["item_id"]=> string(2) "16" 
}
[89]=> array(3) {
     ["keyword"]=> string(10) "biomedical" 
     ["url"]=> string(10) "biomedical" 
     ["item_id"]=> string(2) "34" 
} 
[93]=> array(3) { 
     ["keyword"]=> string(10) "biomedical" 
     ["url"]=> string(10) "biomedical" 
     ["item_id"]=> string(2) "35" 
} 

I want to combine the options that have the same keyword/url.

Just need to check if keyword matches.

The final format needs to be something that jquery autocomplete can accept, where I can assign the text to keyword and the value to url, id to the item_id.

There were only two keys in the array before and I would combine matches this way.

  foreach ($searchArray as $row)
  {  
       $combineMatches[ $row['keyword'] ][] = $row['item_id'];        
  }

result after using json_encode():

"anthropologist":["27","37"],  
"biomedical":["34","35"],  
"m.s.":["18","19","23"]  

What I currently have:

$combineMatches = array();    
foreach ($searchArray as $row)
{         
     $match = 
 array_search($row['keyword'],array_column($combineMatches,'keyword'));
     if($match){
        $combineMatches[$match]['item_id']+= $row['item_id'];
     }else{
        array_push($combineMatches, [
           'keyword' => $row['keyword'],
           'url' => $row['url'],
          'item_id' => array_push($row['item_id'])
       ]);      
     }    
 }

Result:

[7]=> array(3)
{    
    ["keyword"]=> string(8) "theology"   
    ["url"]=> string(8) "theology"   
    ["item_id"]=> NULL   
}   
[13]=> array(3) 
{  
    ["keyword"]=> string(7) "writing"   
    ["url"]=> string(7) "writing"   
    ["item_id"]=> NULL   
}  

How do I add to the array column of just item_id ? Which I see is a string, but I need as an array.

This gets JSON encoded in the end of the PHP and read by jquery autocomplete.

Upvotes: 0

Views: 70

Answers (1)

hpgodwin
hpgodwin

Reputation: 23

Thank you for pointing out the string/array issue.
I changed how to add to the third key if there is a match, and if there isn't a match the solution was changing the array_push to just array.

$combineMatches = array();
foreach ($searchArray as $row)
{
   $match=array_search($row['keyword'],array_column($combineMatches,'keyword'));
   if($match){
      $combineMatches[$match]['item_id'][] = $row['item_id'];
   }else{

        array_push($combineMatches, [
           'keyword' => $row['keyword'],
           'url' => $row['url'],
          'item_id' => array($row['item_id'])
       ]);

   }    
}

Upvotes: 1

Related Questions