rafiaTech rafiaTech - 1 year ago 88
PHP Question

Compare PHP arrays for same Value

I have an array called parts and contains 7000 items. I have another array that called images and contains 34000 items. What I'm trying to do is get the part number from array 1 and look in the images array to see if there is a match. If a match is found then insert the image path and part id to a table. Here is an example:

This one item of the parts array

array:8 [▼
"id" => 1
"rank" => 0
"product_category_id" => "5"
"name" => "BRACKETS, METAL"
"part_num" => "100G"
"description" => "Gold Line aluminum bracket back mounting"
"created_at" => "-0001-11-30 00:00:00"
"updated_at" => "-0001-11-30 00:00:00"

Images array

array:7 [▼
0 => "100G_3Q_H.jpg"
1 => "13VX_3Q_L.jpg"
2 => "2025_TS_1.jpg"

So as you can see I'm trying to see if part_num 100G matches the image name in the images array. if it does get the image name and the part id from the parts array.

Any help is much appreciated.

BTW I'm using Laravel 5.2


Answer Source

First create an array of all part numbers.

Then loop through the images, split out the part number and check if it exists in the part numbers array.

If it does then add it to an array of images for that part number.

You can then either filter out the empty part number arrays or discard them when adding the images to the database.

foreach ($parts as $part) {
  $imageMatches[$part['part_num']] = [];

foreach ($partImages as $image) {
  $imageParts = explode('_', $image);
  $imageNum = $imageParts[0];

  if (array_key_exists($imageNum, $imageMatches)) {
    array_push($imageMatches[$imageNum], $image);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download