I pull one array from a data and one array from an API.
API Array (array1)
...
[71] => Array
(
[id] => integer
[name] => example_name
[logo] => url_of_image
[lang] => en
)
...
Database API (array2)
...
Array(
[0] => integer
[1] => integer
}
...
I want to use array2 to find any instances of the ID in array1, if they exist then unset the key.
Array diff doesn't work with multidimensional. There isn't a common key The values are dynamic so i can't hard code them Array filter won't take multi commands and doing a foreach results in an error
Notice: Array to string conversion in
PHP 5.6.
foreach($array2 as $key => $value) {
foreach($array1 as $key1 => $value1) {
if ($value1 == $value) {
unset($arrat2[$key])
}
}
}
I had this buried somewhere to filter out languages i thought i could stick a foreach inside the function but that throws an array to string conversion.
$filtered = array();
$filtered = array_filter($array1, function($el) { return ($el['lang'] == "en"); });
Something like:
$result = array();
foreach($array2 as $value) {
$result = array_filter($array1, function($ee) { return ($ee['id'] != $value); });
}
Results in:
Notice: Undefined variable: value i
Var dumps array 2:
array(2) {
[0]=>
array(1) {
["id"]=>
string(8) "random integer"
}
[1]=>
array(1) {
["id"]=>
string(9) "random integer"
}
}
var dumps array 1:
array(151) {
[0]=>
array(4) {
["id"]=>
int(integer 1)
["name"]=>
string(7) "example name 1"
["logo"]=>
string(97) "image1.png"
["lang"]=>
string(2) "en"
}
[1]=>
array(4) {
["id"]=>
int(integer 2)
["name"]=>
string(10) "example name 2"
["logo"]=>
string(100) "image2.png"
["lang"]=>
string(2) "en"
}
[2]=>
array(4) {
["id"]=>
int(integer 3)
["name"]=>
string(9) "example name 3"
["logo"]=>
string(99) "image3.png"
["lang"]=>
string(2) "en"
}
great answer, also had to make sure my two values were both integers being compared.
foreach(), I don't see why this approach wouldn't work if you are doing it correctly.array_filterwork? You supply the callback that decides if an element gets tossed or not.