“Réduction du tableau PHP” Réponses codées

réduction réduit le tableau associatif PHP

$assoc_arr = array_reduce($arr, function ($result, $item) {
    $result[$item['text']] = $item['id'];
    return $result;
}, array());
Difficult Dormouse

Réduction du tableau PHP

<?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:\n" . var_export($array, true) . "\n";

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

print "The reduced array with new indexes:\n" . var_export($array, true) . "\n";
SAMER SAEID

Réponses similaires à “Réduction du tableau PHP”

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code