Here is my PHP array:
Array
(
[0] => stdClass Object
(
[item] => 'banana'
[picture] => ''
)
[1] => stdClass Object
(
[item] => 'apple'
[picture] => 'asdkls.jpg'
)
[2] => stdClass Object
(
[item] => 'orange'
[picture] => 'sda.jpg,sf.jpg,ffd.jpg'
)
[3] => stdClass Object
(
[item] => 'pinapple'
[picture] => ''
)
[4] => stdClass Object
(
[item] => 'appricot'
[picture] => ''
)
)
I want to remove all the entries from this array where the picture index is empty, and realign the array with new indices.
My desired output is
Array
(
[0] => stdClass Object
(
[item] => 'apple'
[picture] => 'asdkls.jpg'
)
[1] => stdClass Object
(
[item] => 'orange'
[picture] => 'sda.jpg,sf.jpg,ffd.jpg'
)
)
I have tried
array_values(array_column($csv_arr, NULL, "picture"));
and also
array_filter($csv_arr, function($k) {
return $k == 'picture';
}, ARRAY_FILTER_USE_KEY);
…but both methods don’t seem to work for me. Guidance is much appreciated.
>Solution :
Your first attempt won’t work because your array indices contain objects, not simple strings.
There are a couple of problems with your second attempt, but it’s closer:
-
You’ve specifically told array_filter to only supply the key to the callback. Therefore you can’t then inspect the picture property inside the value of each item to see if it’s empty or not
-
Once you fix that, the value passed in will be an object rather than a simple string, because that’s what your array contains
-
The picture property of that object will never equal the string "picture"…none of your items contain that text (and it wouldn’t make sense if they did). Instead you should test whether the picture property is empty or not (since removing the empty ones is your stated goal).
Here is a version which fixes those problems:
$output = array_filter($csv_arr, function($v, $k) {
return !empty($v->picture);
}, ARRAY_FILTER_USE_BOTH);
print_r($output);
Note the use of the value and key parameters in the callback, the object property notation to gain access to the "picture" property within each object, and the !empty to only return the value into the results if that picture property isn’t empty.
This outputs:
Array
(
[1] => stdClass Object
(
[item] => apple
[picture] => asdkls.jpg
)
[2] => stdClass Object
(
[item] => orange
[picture] => sda.jpg,sf.jpg,ffd.jpg
)
)
Live demo: https://3v4l.org/9DUqJ
Reference documentation: https://www.php.net/manual/en/function.array-filter.php