Asked  1 Year ago    Answers:  5   Viewed   24 times

I have two arrays of the form

Array1:
[0]=> Array([name] => foo [id] => 12)
[1]=> Array([name] => bar [id] => 34)

Array2:
[0]=>Array([name] => bar [id]=> 34)
[1]=>Array([name] => baz [id]=> 56)

The arrays come from a database and any two pairs can have the same name but ID's are unique. I am trying to compare the arrays by ID likes so:

$one_not_two = array_diff($array1[id], $array2[id]);
but that does not return anything. I also tried
$one_not_two = array_diff($array1[id], $array2[id]);
which returned an error "argument is not an array." Originally I got around it by extracting the IDs into a one-dimensional array and just comparing those but now a new feature requires me to compare the pairs. Any advice?

PS Our servers are running php 5.3 if that makes any difference.

 Answers

1

Because the arrays are multidimensional you have to extract the ids like this:

$ids1 = array();
foreach($array1 as $elem1)
    $ids1[] = $elem1['id'];

$ids2 = array();
foreach($array2 as $elem2)
    $ids2[] = $elem2['id'];

$one_not_two = array_diff($ids1,$ids2);

For your specific question, check out array_diff() with multidimensional arrays

Saturday, May 29, 2021
 
etsous
 
1

Yes, you may trust it. All ways of interpolation a variable are covered in the documentation pretty well.

If you want to have a reason why this was done so, well, I can't help you there. But as always: PHP is old and has evolved a lot, thus introducing inconsistent syntax.

Thursday, April 1, 2021
 
Kemrop
 
1

You can sort a collection with sort methods by a given key:

$sorted = $collection->sortByDesc('status');
Thursday, April 1, 2021
 
DCD
 
DCD
3

What about this:

function convert($array) {
    return (count($array) === 0) ? "" : $array;
}

$empty_array = array();
$empty_array = convert($empty_array);

This will simply convert it into a empty string if the array is empty.

An object is somewhat more complicated but you can just use get_object_vars():

function convert($object) {
    return (count(get_object_vars($object)) === 0) ? "" : $object;
}

Nb.: You cannot check an object on private variables.

Thursday, April 1, 2021
 
PHLAK
 
2

Use the indexes of one of the sub-arrays to access all the other sub-arrays:

foreach ($array['item_id'] as $i => $item_id) {
    $request_explanation = $array['request_explanation'][$i];
    $quantity = $array['quantity'][$i];
    // repeat this for all the columns
    // Now you can insert all these variables into the database
}
Saturday, May 29, 2021
 
Dail
 
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :