Grouping PHP array andrey понедельник, 14 апреля 2014 г. No Comment

When we have a same ids for multiple array values, we can group those array values for easy handling.

Consider if we have a array like this,
Array
(
[0] => Array
(
[id] => 96
[shipping_no] => 212755-1
[part_no] => reterty
[description] => tyrfyt
[packaging_type] => PC
)

[1] => Array
(
[id] => 96
[shipping_no] => 212755-1
[part_no] => dftgtryh
[description] => dfhgfyh
[packaging_type] => PC
)

[2] => Array
(
[id] => 97
[shipping_no] => 212755-2
[part_no] => ZeoDark
[description] => s%c%s%c%s
[packaging_type] => PC
)

)
If we want to group the above array by `id`, we can use this following piece of code,
$result = array();
foreach ($arr as $data) {
$id
= $data['id'];
if (isset($result[$id])) {
$result
[$id][] = $data;
} else {
$result
[$id] = array($data);
}
}
So, the  print_r($result) result will be,
Array
(
[96] => Array
(
[0] => Array
(
[id] => 96
[shipping_no] => 212755-1
[part_no] => reterty
[description] => tyrfyt
[packaging_type] => PC
)

[1] => Array
(
[id] => 96
[shipping_no] => 212755-1
[part_no] => dftgtryh
[description] => dfhgfyh
[packaging_type] => PC
)
)
[97] => Array
(
[0] => Array
(
[id] => 97
[shipping_no] => 212755-2
[part_no] => ZeoDark
[description] => s%c%s%c%s
[packaging_type] => PC
)

)
When we have a same ids for multiple array values, we can group those array values for easy handling.

Consider if we have a array like this,
Array
(
[0] => Array
(
[id] => 96
[shipping_no] => 212755-1
[part_no] => reterty
[description] => tyrfyt
[packaging_type] => PC
)

[1] => Array
(
[id] => 96
[shipping_no] => 212755-1
[part_no] => dftgtryh
[description] => dfhgfyh
[packaging_type] => PC
)

[2] => Array
(
[id] => 97
[shipping_no] => 212755-2
[part_no] => ZeoDark
[description] => s%c%s%c%s
[packaging_type] => PC
)

)
If we want to group the above array by `id`, we can use this following piece of code,
$result = array();
foreach ($arr as $data) {
$id
= $data['id'];
if (isset($result[$id])) {
$result
[$id][] = $data;
} else {
$result
[$id] = array($data);
}
}
So, the  print_r($result) result will be,
Array
(
[96] => Array
(
[0] => Array
(
[id] => 96
[shipping_no] => 212755-1
[part_no] => reterty
[description] => tyrfyt
[packaging_type] => PC
)

[1] => Array
(
[id] => 96
[shipping_no] => 212755-1
[part_no] => dftgtryh
[description] => dfhgfyh
[packaging_type] => PC
)
)
[97] => Array
(
[0] => Array
(
[id] => 97
[shipping_no] => 212755-2
[part_no] => ZeoDark
[description] => s%c%s%c%s
[packaging_type] => PC
)

)
by Jillur Rahman

Jillur Rahman is a Web designers. He enjoys to make blogger templates. He always try to make modern and 3D looking Templates. You can by his templates from Themeforest.

Follow him @ Twitter | Facebook | Google Plus

No Comment