Trading Post LLC
Trading Post LLC

Reputation: 53

Array to String Conversion when not echoing

I am comparing the contents of two different databases that contain product data (one for my brick and mortar store, and one for my webstore). I do an array_diff to check for the new/old values, and then take that output and compare it to another array using array_diff, and get the array to string conversion error. I am presenting the two lines that should be the main issue, if you need more information, please ask and I am happy to provide. $webArray and $pdArray are both outputs from a mysqli query. The point of these two lines is to subtract the inventory ids from the brick and mortar from the webstore inventory (to get the list of sold items), then subtract that result from the webstore database. Thank you guys so much!

$soldItems = array_diff ($webArray, $pdArray);
$finalArray = array_diff ($webArray, $soldItems);

Sample code of what's contained in each array:

Sold items Array data

Array ( [product_id] => 75759 )

Sold items Array data:

Array ( [product_id] => 75839 )

Web Array data:

 Array ( [product_id] => 61822,
         [product_id] => 61825 )

Apparently pdArray is empty. But why would that throw that error instead of just returning the array without changes?
So, I checked the Duplicate answer thread, and their problem was that one array was single-dimensional and the other was multi. The sample output above shows that they are multi dimensional.

Upvotes: 1

Views: 130

Answers (2)

Andreas
Andreas

Reputation: 23958

I think array_column is far easier to read than a function with serial and unserial and array_map.
Array_column flattens an array and returns an array that you can use with array_diff.

$soldItems = [
  ['product_id' => 75759],
  ['product_id' => 75839]
];

$webItems = [
  ['product_id' => 61822],
  ['product_id' => 61825],
];

$paidItems = [
  ['product_id' => 61822],
];

$diff = array_diff(array_column($webItems, 'product_id'), array_column($soldItems,'product_id'));
$diff = array_diff($diff, array_column($paidItems, 'product_id'));

print_r($diff); //61825

https://3v4l.org/IcPlb

The reason you get array to string error is because array_diff expects string, float or integer inputs not arrays.

Upvotes: 1

blupointmedia
blupointmedia

Reputation: 604

Here is a method that will give you array_diff on multi-dimensional arrays.

$soldItems = [
  ['product_id' => 75759],
  ['product_id' => 75839]
];

$webItems = [
  ['product_id' => 61822],
  ['product_id' => 61825],
];

$paidItems = [
  ['product_id' => 61822],
];

$diff = getProductDiffs($webItems, $soldItems);
$diff = getProductDiffs($diff, $paidItems);

print_r($diff);

function getProductDiffs($arr1, $arr2) {
  $diff = array_diff(array_map('serialize',$arr1), array_map('serialize',$arr2));
  return array_map(function($item){
    return unserialize($item);
  }, $diff);
}

Upvotes: 0

Related Questions