Search
 
SCRIPT & CODE EXAMPLE
 

PHP

php reduce

$numbers = [1,2,3,4,5];

function add ($array) {
    return array_reduce($array, fn($acc, $val) => $acc + $val, 0);
}

echo add($numbers);
Comment

PHP Array Reduce

<?php

$array = [
    [
        'tag_id' => "6291",
        'az' => 5,
    ],
    [
        'tag_id' => "6291",
        'az' => 4,
    ],
    [
        'tag_id' => "6311",
        'az' => 4,
    ],
    [
        'tag_id' => "6427",
        'az' => 4,
    ]
];

$tag_id_indexes = []; // To store the index of the first tag_id found.

array_walk(
    $array,
    function ($sub_array, $index) use (&$array, &$tag_id_indexes) {
        // Store the index of the first tag_id found.
        if (!isset($tag_id_indexes[$sub_array['tag_id']])) {
            $tag_id_indexes[$sub_array['tag_id']] = $index;
        }
        else { // This tag_id already exists so we'll combine it.
            // Get the index of the previous tag_id.
            $first_tag_id_index = $tag_id_indexes[$sub_array['tag_id']];
            // Sum the az value.
            $array[$first_tag_id_index]['az'] += $sub_array['az'];
            // Remove this entry.
            unset($array[$index]);
        }
    }
);

print "The reduced array but with the original indexes:
" . var_export($array, true) . "
";

// If you want new indexes.
$array = array_values($array);

print "The reduced array with new indexes:
" . var_export($array, true) . "
";
Comment

PREVIOUS NEXT
Code Example
Php :: how to change javascript value to php value 
Php :: laravel share on whatsapp link 
Php :: get post url from post id wordpress 
Php :: dont show file type in url 
Php :: laravel find by 
Php :: br php 
Php :: laravel withHas 
Php :: str_replace php 
Php :: root directory in php 
Php :: wordpress require file from plugins folder 
Php :: how to add attributes to an object in php 
Php :: php date start of day 
Php :: How do I check if a string contains a specific word? 
Php :: php timer 
Php :: laravel difference between fill and update 
Php :: time in php 
Php :: php search the key off bigger value 
Php :: convert query result to array php 
Php :: PHP time limit (max_execution_time): 
Php :: laravel validator make custom message 
Php :: how to build jquery messages notification with php and mysq 
Php :: How to request and display data from db in larave 
Php :: object php 
Php :: register_post_type wordpress 
Php :: laravel group route controller 
Php :: get array key based on value php 
Php :: laravel reduce 
Php :: wordpress get post body 
Php :: How do I get the current date and time in PHP? 
Php :: unset session key 
ADD CONTENT
Topic
Content
Source link
Name
9+7 =