Search
 
SCRIPT & CODE EXAMPLE
 

PHP

array reduce associative array php

$assoc_arr = array_reduce($arr, function ($result, $item) {
    $result[$item['text']] = $item['id'];
    return $result;
}, array());
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 :: startsWith() and endsWith() functions in PHP 
Php :: check current pages is a child page wordpress 
Php :: codeigniter table list 
Php :: self submit form php 
Php :: how validate array in laravel in request 
Php :: Laravel randomise data from database 
Php :: php json request get value of an array element 
Php :: laravel cron job on shared hosting 
Php :: carbon diff 
Php :: iteration in php 
Php :: how to send ajax request in laravel 
Php :: item count in cart quantitiy woocommerce 
Php :: display all errors in blade laravel 
Php :: get taxonomy term meta by id 
Php :: php sort multi dimensional array 
Php :: LARAVEL CREAT NEW TEST 
Php :: laravel log could not be opened fix 
Php :: laravel update table column 
Php :: php fix array index 
Php :: image store short method in laravel 
Php :: take file data in variable php 
Php :: redirect woocommerce thank you 
Php :: create seed file laravel 
Php :: php check if folder exists 
Php :: unset by key name php 
Php :: supervisor configuration for laravel queue 
Php :: create new laravel 9 project 
Php :: get featured image id wordpress 
Php :: laravel log build custom channel 
Php :: php get highest key in array 
ADD CONTENT
Topic
Content
Source link
Name
8+5 =