Here is a sample data set
$all_items = array ( $a1 = array ( name => "item1", description => "item 1", item_key => 123 ), $a2 = array ( name => "item2", description => "item 2", item_key => 456 ), $a3 = array ( name => "item3", description => "item 3", item_key => 789 ) ); $invoice_items = array ( $b1 = array ( item_key => 123, desc => "1item" ), $b2 = array ( item_key => 456, desc => "2item" ), $b3 = array ( item_key => 123, desc => "3item" ), $b4 = array ( item_key => 345, desc => "4item" ), $b5 = array ( item_key => 123, desc => "5item" ), $b6 = array ( item_key => 345, desc => "6item" ), $b7 = array ( item_key => 123, desc => "7item" ) );
So the goal here is that whenever there is an invoice item that matches an item's item_key
, I want to put the array of invoice items into a new array. So in this example, I think the result I want is something like this
Array ( [0] => Array ( [0] => Array ( [name] => item1 [description] => item 1 [item_key] => 123 ), [1] => Array ( [item_key] => 123 [desc] => 1item ), [2] => Array ( [item_key] => 123 [desc] => 3item ), [3] => Array ( [item_key] => 123 [desc] => 5item ), [4] => Array ( [item_key] => 123 [desc] => 7item ) ) [1] => Array ( [0] => Array ( [name] => item2 [description] => item 2 [item_key] => 456 ), [1] => Array ( [item_key] => 456 [desc] => 2item ), ) [2] => Array ( [0] => Array ( [name] => item3 [description] => item 3 [item_key] => 789 ) ) )
Any suggestions?
I've tried just comparing the arrays and pushing the values, but I just end up with a big array, kind of back to where I started. I'm still a little new to PHP and may not be familiar with some array methods
The structure of the resulting array is the same as you described in your question above.
But there is a contradiction between your result set and your comment "...merge the invoice_item array into a new array". Your result array has the invoice items appended, hence my code above.
Now, this solution does create a new key - here called "descs" - an array in the invoice items under this key:
Since the item_keys in these "descs" array entries are redundant, you can remove them and just create a string array:
Output:
Please note that your input arrays all have assignment statements in their construction ($a1 = ..., $a2 = ..., etc.). This doesn't make much sense unless you need these variables later. If so, encoding is more readable and better: