0

I have an 2d array that contains a 'title' and 'url' (both strings) as shown below. Is it possible to check for duplicates in the 'url' and if they exist, delete the corresponding 'title' too?

array
      0 => 
        array
          'title' => string 'China - Wikipedia, the free encyclopedia'
          'url' => string 'http://en.wikipedia.org/wiki/China'
      1 => 
        array
          'title' => string 'China'
          'url' => string 'http://www.state.gov/r/pa/ei/bgn/18902.htm'
      2 => 
        array
          'title' => string 'China | World news | The Guardian'
          'url' => string 'http://www.guardian.co.uk/world/china'
      3 => 
        array
          'title' => string 'China Travel Information and Travel Guide - Lonely Planet'
          'url' => string 'http://www.lonelyplanet.com/china'
      4 => 
        array
          'title' => string 'ChinaToday.com'
          'url' => string 'http://www.chinatoday.com/'
3
  • Which title? The first one? The last one? All? What is the problem you've faced? Commented Jul 10, 2012 at 11:43
  • 2
    The only correct answer to this would be "Yes, it is possible". Commented Jul 10, 2012 at 11:52
  • Yes it is possible, but I would suggest to setup a small class that has 'title' and 'url' as its attributes with a simple constructor that populates them, then use a one-dimensional array. Commented Jul 10, 2012 at 11:54

3 Answers 3

1

Try this function it could do the job

function super_unique($array,$key)
{
   $temp_array = array();

   foreach ($array as &$v) {

       if (!isset($temp_array[$v[$key]]))

       $temp_array[$v[$key]] =& $v;

   }
   $array = array_values($temp_array);
   return $array;
}

$yourearray = super_unique($arr,'url');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help everyone. You guys are fast!
1

Or if you are happy with using the last value of the url you could

foreach($array as $subarray) {
    $output[$subarray['url']] = $subarray['title'];
}

Comments

0

Try something like this:

$originals = array();

foreach($array as $key => $value) {
   if(!isset($originals[$value['url']])) {
      $originals[$value['url']] = true;
   }
   else {
      // exists already, delete entry
      unset($array[$key]);
   }
}

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.