How to group an array of associative arrays by key in PHP - ARTIKEL SALIM TEKNOLOGI

Latest

Artikel Bermanfaat Untuk Kita Semua

Sabtu, 09 Mei 2020

How to group an array of associative arrays by key in PHP



Ini adalah function untuk group berdasarkan objek json yang kita mau, monggo di ambil saya juga dapat dari > https://ourcodeworld.com/articles/read/762/how-to-group-an-array-of-associative-arrays-by-key-in-php
<?php
/**
 * Function that groups an array of associative arrays by some key.
 * 
 * @param {String} $key Property to sort by.
 * @param {Array} $data Array that stores multiple associative arrays.
 */
function group_by($key, $data) {
    $result = array();

    foreach($data as $val) {
        if(array_key_exists($key, $val)){
            $result[$val[$key]][] = $val;
        }else{
            $result[""][] = $val;
        }
    }

    return $result;
}

////////////////////////////////////////////////////////////////////////
example array:
<?php 

$data = array(
    array(
        "id" => 1,
        "name" => "Bruce Wayne",
        "city" => "Gotham",
        "gender" => "Male"
    ),
    array(
        "id" => 2,
        "name" => "Thomas Wayne",
        "city" => "Gotham",
        "gender" => "Male"
    ),
    array(
        "id" => 3,
        "name" => "Diana Prince",
        "city" => "New Mexico",
        "gender" => "Female"
    ),
    array(
        "id" => 4,
        "name" => "Speedy Gonzales",
        "city" => "New Mexico",
        "gender" => "Male"
    )
);

///////////////////////////////////////////////
usage :
<?php

// Group data by the "gender" key 
$byGroup = group_by("gender", $data);

// Dump result
echo "<pre>" . var_export($byGroup, true) . "</pre>";

Tidak ada komentar:

Posting Komentar