vincej's avatar
Level 15

How to find the differences between two arrays when they are in different formats?

I have two arrays, $nodes and $result. I want to create a third array, showing the differences. This might have been easy using something like array_diff() however, my two arrays are in a different format and here is where I am getting into trouble:

$nodes array is the result of a raw SQL query and looks like this ( abbreviated):

array (size=12)
  0 => 
    object(stdClass)[434]
      public 'name' => string 'Architectural' (length=13)
      public 'depth' => int 4
  1 => 
    object(stdClass)[435]
      public 'name' => string 'Asphalt' (length=7)
      public 'depth' => int 3
  2 => 
    object(stdClass)[436]
      public 'name' => string 'Cedar' (length=5)
      public 'depth' => int 3

$resultarray is the outcome of filtering the $nodes array with a for loop to find those nodes with a certain depth. It looks like this:

array (size=3)
  0 => string 'Materials' (length=9)
  1 => string 'Root' (length=4)
  2 => string 'Services' (length=8)

I want to compare the two arrays, and find those values which do not appear in the $result array.

I have tried to get them into the same format with $nodes->toArray() but that doesn't work.

Any ideas how I might how I can find the differences in two arrays?

Many thanks !

0 likes
4 replies
martinbean's avatar

@vincej You first need to define the rule for “different”. If the arrays are different shapes, then PHP is always going to think they’re different. You need to define what is the “same” and what is “different”.

Get the data in the same “shape”, then try and diff them.

vincej's avatar
Level 15

good comment. For me "different" means different values. $result is a subset of $nodes. I which to create a new array where the values from $result are no longer included. I hope that makes sense. My challenge is I don't know how to get them into the same shape.

vincej's avatar
vincej
OP
Best Answer
Level 15

Got 'er done. I hope this might help someone else.

Instead of trying to array_diff() the $nodes and the $result array, both of which are derived from the same sql query, I introduced a second query creating the array $categories. Although this array was a collection, it was not multi dimensional. So, I could convert it to a plain array with toArray(). From there I could use array_diff($categories, $result) and got what I needed.

cheers.

jlrdw's avatar

@vincej good one, I use arrays in accounting programs sometimes and I have this now bookmarked.

1 like

Please or to participate in this conversation.