array reduce associative array php
$assoc_arr = array_reduce($arr, function ($result, $item) {
$result[$item['text']] = $item['id'];
return $result;
}, array());
array reduce associative array php
$assoc_arr = array_reduce($arr, function ($result, $item) {
$result[$item['text']] = $item['id'];
return $result;
}, array());
php array_reduce
PHP function array_reduce(array $array, callable $callback, mixed $initial) mixed
-----------------------------------------------------------------------------
Iteratively reduce the array to a single value using a callback function.
Parameters:
array--$array--The input array.
callable--$callback--The callback function. Signature is callback ( mixed $carry , mixed $item ) : mixed
mixed-$carry
The return value of the previous iteration; on the first iteration it holds the value of $initial.
mixed-$item
Holds the current iteration value of the $input
mixed--$initial--[optional] If the optional initial is available, it will be used at the beginning of the process,
or as a final result in case the array is empty.
Returns: the resulting value.
If the array is empty and initial is not passed, array_reduce returns null.
Example use:
============
#1
$numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
function sum( $oldvalue, $newvalue ) {
return $oldvalue + $newvalue;
}
$data = array_reduce( $numbers, 'sum' );
print_r( $data );
/*---------------------------*/
#2
$numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
function sum( $oldvalue, $newvalue ) {
if ( $newvalue % 2 == 0 ) {
return $oldvalue + $newvalue;
}
return $oldvalue;
}
$data = array_reduce( $number, 'sum' );
print_r( $data );
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us