phparraysmultidimensional-arrayfilterarray-difference

Get values from a 2d array which are not found in another flat array


We upload a lot of photos to WordPress. We do not use them all though. The unused ones remain "attached" to the post it's not in which makes it hard to go back and delete it.

I've build 2 arrays. One array contains all of the images from the post content ($postImages). The other array contains all of the images WordPress database have attached to the post ($mediaImages).

I'm trying to identify which images appear in the database, but not in the post. This way I can detach the image from within the database.

I'm using array_diff to compare the two arrays, however it's not showing the odd man out. It appears to be showing the matches.

Here's my arrays:

Call this one $postImages:

var_dump($postImages);

array(3) {
  [2]=>
  string(64) "http://mywebsite.com/wp-content/uploads/2013/11/photoblog1.jpg"
  [0]=>
  string(64) "http://mywebsite.com/wp-content/uploads/2013/11/photoblog2.jpg"
  [1]=>
  string(64) "http://mywebsite.com/wp-content/uploads/2013/11/photoblog3.jpg"
}

And $mediaImages:

var_dump($mediaImages);

array(4) {
  [1]=>
  array(1) {
    [0]=>
    string(64) "http://mywebsite.com/wp-content/uploads/2013/11/photoblog1.jpg"
  }
  [2]=>
  array(1) {
    [0]=>
    string(64) "http://mywebsite.com/wp-content/uploads/2013/11/photoblog2.jpg"
  }
  [0]=>
  array(1) {
    [0]=>
    string(64) "http://mywebsite.com/wp-content/uploads/2013/11/photoblog3.jpg"
  }
  [3]=>
  array(1) {
    [0]=>
    string(62) "http://mywebsite.com/wp-content/uploads/2013/12/IMG_0069.jpg"
  }
}

Here is the output:

$matches = array_diff($postImages, $mediaImages);
print_r($matches);

Array
(
    [2] => http://mywebsite.com/wp-content/uploads/2013/11/photoblog1.jpg
    [0] => http://mywebsite.com/wp-content/uploads/2013/11/photoblog2.jpg
    [1] => http://mywebsite.com/wp-content/uploads/2013/11/photoblog3.jpg
)

Expected output:

Array
(
    [0] => http://mywebsite.com/wp-content/uploads/2013/12/IMG_0069.jpg
)

Solution

  • As Marc B pointed out in the comments, $mediaImages is an array of arrays of strings, while $postimages is just an array of strings.

    You can use array_map() with a custom callback to create the $mediaImages array:

    $mediaImages = array_map(function($item) { 
        return $item[0]; 
    }, $mediaImages);
    

    Also, note that you have the parameters for array_diff() backwards. The correct order is:

    array_diff($arrayToCompareFrom , $arrayToCompareAgainst);
    

    So to compare $postImages against $mediaImages, you'd need:

    $matches = array_diff($mediaImages, $postImages);
    print_r($matches);
    

    Demo.