Here is a code sample
Array
(
[0] => Array
(
[ID] => 1197
)
[1] => Array
(
[ID] => 1078
)
)
I want it to convert into simple index array as:
Array( 1197, 1078 )
I know it can be done by iterating each index and assigning into a temp array. I want a one liner syntax like array_filter do in many cases. Is there any built-in function in PHP which do my task in one line, any mix of statement in one line. I don't want to use it in loops.
If you are using PHP > 5.5.0, you can use array_column:
$ids = array_column($array, 'ID');
On the linked page, you'll find a substitute for older versions:
if(!function_exists("array_column"))
{
function array_column($array,$column_name)
{
return array_map(function($element) use($column_name){return $element[$column_name];}, $array);
}
}
Related
This question already has answers here:
Change the array KEY to a value from sub array
(7 answers)
How can i get sub array value to main array key? [Php] [duplicate]
(2 answers)
Multidimensional indexed array to associative array depending on column value
(2 answers)
Closed 10 months ago.
I have a function that work good in php 7 but in php 8.0.11 has warning
$orders->result = array_map('reset', $orders->result);
E_WARNING: reset(): Argument #1 ($array) must be passed by reference, value given in
Of course, I can use this code instead that but maybe slower than array_map
foreach ($orders->result as $item)
$result[$item[0]['order_id']] = $item[0];
Edit:
before foreach or array_map the output like this
Array
(
[0] => Array
(
[order_id] => 41111909
[shop_id] => 34277
[user_id] => 42363
[status_id] => 4
)
)
after use foreach output like this
Array
(
[41111909] => Array
(
[order_id] => 41111909
[shop_id] => 34277
[user_id] => 42363
[status_id] => 4
)
)
How to solve it ?
The simplest replacement is to make an arrow function (single-expression closure) to get the element for you.
If the arrays are plain lists, so that you're always getting element 0, that's as simple as:
$orders->result = array_map(fn($item) => $item[0], $orders->result);
Another alternative in this case is array_column:
$orders->result = array_colum($orders->result, 0);
If you have other keys, you could use either reset or array_key_first in the callback instead:
$orders->result = array_map(fn($item) => $item[array_key_first($item)], $orders->result);
(I suspect array_key_first will be slightly more efficient, since it doesn't need to manipulate the internal array pointer.)
It's not entirely clear what you're trying to do, but it seems like you are trying to get the first value from nested arrays. You should be able to use a function:
$orders->result = array_map(function($v) { return reset($v); }, $orders->result);
You may also try using current if it does what you need as it doesn't take a reference and the array pointer should already be reset by array_map:
$orders->result = array_map('current', $orders->result);
After the edit the code in question is not re-indexing the array as you show in the before and after. To do that is simple:
$orders->result = array_column($orders->result, null, 'order_id');
I have this type of array,
Array
(
[0] => Array
(
[id] => 0
[fams] => 5
)
[1] => Array --> I want to remove this value using its index, which is "1"
(
[id] => 2
[fams] => 5
)
)
I want to remove that array [1] entirely, using its index, so the condition is - where the ID is match, for example - [id] => 2
Is that possible, to remove a particular value with that specific condition?
and without looping (or any similar method that need to loop the array)
thanks in advance!
FYI - I did try to search around, but, to be honest, I'm not sure what "keyword" do I need to use.
I did try before, but I found, array_search, array_keys - and it seems those 2 are not.
I'm okay, if we need several steps, as long as it did not use "loop" method.
---update
I forgot to mention, that I'm using old PHP 5.3.
array_filter should work fine with PHP 5.3.
The downside of this approach is that array_filter will (internally) iterate over all your array's entries, even after finding the right one (it's not a "short-circuit" approach). But at least, it's quick to write and shouldn't make much of a difference unless you're dealing with very big arrays.
Note: you should definitely upgrade your PHP version anyway!
$array = array (
0 =>
array (
'id' => 0,
'fams' => 5
),
1 =>
array (
'id' => 2,
'fams' => 5
)
);
$indexToRemove = 2;
$resultArray = array_filter($array, function ($entry) use ($indexToRemove) {
return $entry['id'] !== $indexToRemove;
});
Demo: https://3v4l.org/6DXjl
You can use array_search to find the key of a sub-array that has a matching id value (extracted using array_column), and if found, unset that element:
if (($k = array_search(2, array_column($array, 'id'))) !== false) {
unset($array[$k]);
}
print_r($array);
Output:
Array
(
[0] => Array
(
[id] => 0
[fams] => 5
)
)
Demo on 3v4l.org
It should be noted that although there is no explicit loop in this code, array_search and array_column both loop through the array internally.
You can use array_column to make id as index of the sub-array then use unset
$a = array_column($a, null, 'id');//new array id as index
$index = 2;// id to remove
if($a[$index]) unset($a[$index]);
print_r($a);
Working example :- https://3v4l.org/ofMr7
I have a multidimensional array like this:
Array (
[0] => Array
(
[time] => 1364685993
[memberid] => 131
)
[1] => Array
(
[time] => 1364685994
[memberid] => 133
)
[2] => Array
(
[time] => 1364685995
[memberid] => 141
)
)
and a single-dimensional array like this:
Array (
[0] => 131
[1] => 141
[2] => 191
[3] => 205
)
Now I want to remove all Sub-arrays from multidimensional arrays that DOES NOT contain the memberid value from normal array ?
In this case only Subaray[1] to be removed from multidimensional array as it's 'memberid' key value (133) doesn't show in normal array. Those arrays are actually pretty big, so I am not sure what would be fastest way to do it ?
$normalArray = array_flip($normalArray);
$multiDimArray = array_filter($multiDimArray, function ($elem) use ($normalArray) {
return isset($normalArray[$elem['memberid']]);
});
Requires exactly two iterations, one over each array. Key lookups using $normalArray[$elem['memberId']] are blazingly fast. May have some memory overhead due to the functional nature and copies of arrays, use a traditional loop and unset if that's an issue.
First, I would flip the $nomal array to get constant lookup time into the array, like this:
$normal = array_flip( $normal);
Then, you just have to filter the $multidimensional_array by the $normal array with a simple lookup:
$filtered = array_filter( $multidimensional_array, function( $el) use( $normal) {
return isset( $normal[ $el['member_id'] ]);
});
Don't have access to development resources at the moment to test but this should work.
foreach($members as $member => $property) {
if (!in_array($property['member_id'], $id_array)) {
unset($members[$member]);
}
}
$id_array is the 1-dimensional matrix (array) you've put in your question.
Instead of filtering the database results after the fact you may want to use the single-dimensional array in the database query itself.
We do not know what the query, you are using, looks like, but something along these lines would do it:
// The ids from the file
$use_ids = array(131, 141, 191, 205);
// Create a list for the IN clause
$ids = '(' . implode(',', $use_ids) . ')';
// Create the query
$query = <<< SQL
SELECT time, memberid
FROM some_table
WHERE ...
AND memberid IN {$ids}
ORDER BY time
SQL;
// Execute the query, etc.
It is always a good idea to let the SQL handle as much filtering of content as possible.
I want to merge some multidimension arrays and calculate the values of their items. For example :
Array
(
[0] => Array
(
[0] => Array
(
[nr_colete] => 6
)
)
[1] => Array
(
[0] => Array
(
[nr_colete] => 22
)
)
)
I want to get a solution to combine them and get a result such as
Array
(
[0] => Array
(
[nr_colete] => 6 + 22
)
)
Is there a native php function to help me get this result ? I try to found one.
I can't think of one single php native function to do this, but you can do it very simply using a foreach loop.
$sum = 0;
foreach($array AS $k => $value) {
$sum += $value[0]['nr_colete'];
}
Here is the code in action
No native function which will do that directly.But you can use array_column() and array_sum() two native function to get your desired result.
Check below code:-
$final_array[0]['nr_colete'] = array_sum(array_column(array_column($array,0),'nr_colete'));
print_r($final_array);
Output:- https://eval.in/873338
Reference:-
array_column()
array_sum()
I have a multidimensional array in this format
[0] => Array
(
[0] => Supplier
[1] => Supplier Ref
)
I basically need to offset every array with a new field at the beginning, so the outcome should be:
[0] => Array
(
[0] => New Field
[1] => Supplier
[2] => Supplier Ref
)
If I can run a loop through each array using for/foreach then that would be great but I'm struggling to find a good method of doing this. Any ideas?
Thanks
I can think of three straightforward ways
Use a simple foreach and array_unshift
foreach($arr as &$item) {
array_unshift($item, 'new field');
}
Use array_walk to apply array_unshift to each array item (will modify the existing array)
array_walk($array, function(&$item) { array_unshift($item, 'new field'); });
Use array_map and array_unshift (will return a new array – but the arrays inside the original array will be modified nevertheless)
array_map(function(&$item) {
array_unshift($item, 'new field'); return $item;
}, $array);
You can use array_unshift() to offset array within array php. It prepend one or more elements to the beginning of an array.