Extract all ids from array of objects - php

With PHP 7.4, I have associative array with objets :
$array = [
1 => Class {
'id' => 1,
'call' => true,
},
5 => Class {
'id' => 5,
'call' => false,
},
7 => Class {
'id' => 7,
'call' => true,
},
]
I want to extract all the IDs if the call attribute === true.
After searching, I think I should use the array_map function.
$ids = array_map(function($e) {
if (true === $e->call) {
return $e->id;
}
}, $array);
// Return :
array(3) {
[1]=> 1
[5]=> NULL
[7]=> 7
}
But I have two problems with this:
I don't want NULL results
I don't wish to have the associative keys in in my new array. I want a new array ([0=>1, 1=>7])
I know I can do it with a foreach() but I find it interesting to do it with a single PHP function (array_walk or array_map ?)

Create an array which is the call value indexed by the id and then filter it. As the id is the index, then extract the keys for the ids...
$ids = array_keys(array_filter(array_column($array, "call", "id")));
print_r($ids));
Array
(
[0] => 1
[1] => 7
)
Although I think a foreach() is a much more straight forward method.

You probably want array_filter to filter out what you don't want, then you can extract the id:
$ids = array_column(array_filter($array, function($e) {
return $e->call === true;
}), 'id');

You can reduce the array with a callback that conditionally adds each item's id to the "carry" array.
$ids = array_reduce($array, fn($c, $i) => $i->call ? [...$c, $i->id] : $c, []);

Related

Extracting associated value of nested array using unique value in PHP

I am aware that I could use a loop to answer my question, but I was hoping that maybe PHP has a function to do what I am trying to achieve and that someone might know.
Basically I am trying to identify a unique key from a series of arrays and then extract the value of the correlated key in the array.
So basically, from this array:
$myarray = array(array("id" => 1, "label" => "True"), array("id" => 2, "label" => "False"))
I want to be able to find the label value when the id is searched and matched, i.e. $id = 1 should return True.
Any simple functions available to do this without having to write a couple of loops?
It would be one simple loop. But if you are loopofobic, then you can rely on other functions (that acts as loop too):
function find(array $inputs, int $search): ?string
{
$result = array_filter($inputs, fn ($input) => $input['id'] === $search);
return current($result)['label'] ?? null;
}
$myarray = [["id" => 1, "label" => "True"], ["id" => 2, "label" => "False"]];
var_dump(find($myarray, 1)); // string(4) "True"
var_dump(find($myarray, 2)); // string(5) "False"
var_dump(find($myarray, 3)); // NULL
Live Example
you may use the built-in function array_column() for your aim.
$myarray = array(array("id" => 1, "label" => "True"), array("id" => 2, "label" => "False"));
/* label (value) per id (key) in 1-dimensional array.*/
print_r(array_column($myarray,'label','id'));
will return
Array
(
[1] => True
[2] => False
)
so you may adjust the code below.
$myarray = array(array("id" => 1, "label" => "True"), array("id" => 2, "label" => "False"));
$id_val = 1;
$output = isset(array_column($myarray,'label','id')[$id_val]) ? array_column($myarray,'label','id')[$id_val] : 'key not found';
var_dump($output);

Array Filter to fitler arrays in php [duplicate]

This question already has answers here:
How to filter an array by a condition
(9 answers)
Closed 7 months ago.
How can I remove an item based on key for example, $array[testing3] or based on value, for example, Template3 from the below array in php.
$array = array(
'mentor' => 'Template',
'mentor1' => 'Template1',
'testing' => 'Template2',
'testing3' => 'Template3',
'testing4' => 'Template4',
'testing5' => 'Template5',
'testing6' => 'Template6'
);
Let's use array_filter() to achieve the goal.
$array = array(
'mentor' => 'Template',
'mentor1' => 'Template1',
'testing' => 'Template2',
'testing3' => 'Template3',
'testing4' => 'Template4',
'testing5' => 'Template5',
'testing6' => 'Template6'
);
Remove an item in an array, for example, Template3
$filtered_array1 = array_filter($array, function($val) {
return 'Template3' != $val;
});
print_r($filtered_array1);
Remove all elements in an array except Template3 from the array
$filtered_array2 = array_filter($array, function($val) {
return 'Template3' == $val;
});
print_r($filtered_array2);
So far, we used value to filter an array. You can filter an array based on key too. You need to use 3rd argument to the function. There two options for the 3rd argument - ARRAY_FILTER_USE_KEY and ARRAY_FILTER_USE_BOTH. You may use one of them. Let's use ARRAY_FILTER_USE_KEY flag to remove an item based on key, for example, testing3:
$filtered_array3 = array_filter($array, function($key) {
return 'testing3' != $key;
}, ARRAY_FILTER_USE_KEY);
print_r($filtered_array3);
To know more about array_filter() function please refer to this doc
You can use unset() to achieve this:
unset(myArray['testing3']);
You can use unset (https://www.php.net/unset)
$array = array(
'mentor' => 'Template',
'mentor1' => 'Template1',
'testing' => 'Template2',
'testing3' => 'Template3',
'testing4' => 'Template4',
'testing5' => 'Template5',
'testing6' => 'Template6');
unset($array['testing3']);
or if you need to find it by the value you can use the array_search (https://www.php.net/array-search)
// Remove the element if it exists
if($element = array_search("Template3",$array)){
unset($array[$element]);
}
To answer the question brought up in the comments about keeping only the array element you're looking for:
use array_search and overwrite your array (or create a new array from it).
$array = array_search('Template3', $array);

First element of array by condition [duplicate]

This question already has answers here:
Elegant way to search an PHP array using a user-defined function
(7 answers)
Closed 4 years ago.
I am looking for an elegant way to get the first (and only the first) element of an array that satisfies a given condition.
Simple example:
Input:
[
['value' => 100, 'tag' => 'a'],
['value' => 200, 'tag' => 'b'],
['value' => 300, 'tag' => 'a'],
]
Condition: $element['value'] > 199
Expected output:
['value' => 200, 'tag' => 'b']
I came up with several solutions myself:
Iterate over the array, check for the condition and break when found
Use array_filter to apply condition and take first value of filtered:
array_values(
array_filter(
$input,
function($e){
return $e['value'] >= 200;
}
)
)[0];
Both seems a little cumbersome. Does anyone have a cleaner solution? Am i missing a built-in php function?
The shortest I could find is using current:
current(array_filter($input, function($e) {...}));
current essentially gets the first element, or returns false if its empty.
If the code is being repeated often, it is probably best to extract it to its own function.
There's no need to use all above mentioned functions like array_filter. Because array_filter filters array. And filtering is not the same as find first value. So, just do this:
foreach ($array as $key => $value) {
if (meetsCondition($value)) {
$result = $value;
break;
// or: return $value; if in function
}
}
array_filter will filter whole array. So if your required value is first, and array has 100 or more elements, array_filter will still check all these elements. So, do you really need 100 iterations instead of 1? The asnwer is clear - no.
Your array :
$array = [
['value' => 100, 'tag' => 'a'],
['value' => 200, 'tag' => 'b'],
['value' => 300, 'tag' => 'a'],
];
To find the entries via conditions, you could do this
$newArray = array_values(array_filter($array, function($n){ return $n['value'] >= 101 && $n['value'] <= 400; }));
With this you can set to values, min and max numbers.
if you only want to set a min number, you can omit the max like this
$arrayByOnlyMin = array_values(array_filter($array, function($n){ return $n['value'] >= 199; }));
This would return :
array(2) {
[0]=>
array(2) {
["value"]=>
int(200)
["tag"]=>
string(1) "b"
}
[1]=>
array(2) {
["value"]=>
int(300)
["tag"]=>
string(1) "a"
}
}
so calling $arrayByOnlyMin[0] would give you the first entry, that matches your min condition.

Remove specific records from associative array key in php

Hi I have an array that contains two arrays that has the following structure:
categories [
"lvl0" => array:2 [
0 => "Cleaning"
1 => "Bread"
]
"lvl1" => array:2 [
0 => null
1 => "Bread > rolls"
]
]
I would like to remove any records of NULL from the 'lvl1' array but have not been able to find the correct method to do this.
I have tried:
array_filter($categories['lvl1'])
But this also removes all records associated to lvl1 and not just the NULL ones.
Any help would be greatly appreciated.
Thanks
array_filter() takes a callback as the second argument. If you don't provide it, it returns only records that aren't equal to boolean false. You can provide a simple callback that removes empty values.
array_filter() also uses a copy of your array (rather than a reference), so you need to use the return value.
For instance:
$categories = [
"lvl0" => [
"Cleaning",
"Bread"
],
"lvl1" => [
null,
"Bread > rolls"
]
];
$lvl1 = array_filter($categories['lvl1'], function($value) {
return !empty($value);
});
var_dump($lvl1);
That will return:
array(1) {
[1] =>
string(13) "Bread > rolls"
}
I was having the same issue on my last working day.Generally for associative array array_filter() needs the array key to filter out null, false etc values. But this small function help me to filter out NULL values without knowing the associative array key. Hope this will also help you, https://eval.in/881229
Code:
function array_filter_recursive($input)
{
foreach ($input as &$value)
{
if (is_array($value))
{
$value = array_filter_recursive($value);
}
}
return array_filter($input);
}
$categories = [
"lvl0" => [
"Cleaning",
"Bread"
],
"lvl1" => [
null,
"Bread > rolls"
]
];
$result = array_filter_recursive($categories);
print '<pre>';
print_r($result);
print '</pre>';
Output:
(
[lvl0] => Array
(
[0] => Cleaning
[1] => Bread
)
[lvl1] => Array
(
[1] => Bread > rolls
)
)
Ref: http://php.net/manual/en/function.array-filter.php#87581
Robbie Averill who commented on my post with the following solved the issue:
$categories['lvl1'] = array_filter($categories['lvl1']);

Retrieve value of child key in multidiensional array without knowing parent key

Given this multidimensional array, I'm trying to retrieve the value of one of the child keys:
$movieCast = Array(
'1280741692' => Array(
...
, 'userid' => 62
, 'country_id' => '00002'
...
)
, '1280744592' => Array(
...
, 'userid' => 62
, 'country_id' => '00002'
...
)
)
How can I retrieve the value of country_id?
The top-level array key could be anything and the value of country_id will always be the same for a specific user. In this example, user #62's country_id will always be 00002.
You have to iterate through the outer array:
foreach ($outer as $inner) {
//do something with $inner["country_id"]
}
Another option is to build an array with the contry_ids (example uses PHP >=5.3 functionality, but that can be worked around easily in earlier versions):
array_map(function ($inner) { return $inner["country_id"]; }, $outer);
EDIT If the ids are all the same, even easier. Do:
$inner = reset($outer); //gives first element (and resets array pointer)
$id = $inner["country_id"];
a more general-purpose solution using php 5.3:
function pick($array,$column) {
return array_map(
function($record) use($column) {
return $record[$column];
},
$array
);
}
You need to use this:
array_column($movieCast, 'country_id')
The result will be:
array (
0 => '00002',
1 => '00002',
)

Categories