Hello I am trying to rebuild an array where the key category = DESKTOPS. Here is an example of my array: $dummyData['data'][$counter] = array('item' => $A, 'ff' => $B, 'proc' => $C, 'mfgr' => $D, 'category' => $E, 'purchaseCost' => $F, 'qty' => $G);
My array looks like this example:
<?php
$data =
array (
5 =>
array (
'item' => '600 G1',
'ff' => 'SFF',
'proc' => 'i5',
'mfgr' => 'HP',
'category' => 'DESKTOPS',
'purchaseCost' => '$56.00',
'qty' => '4',
),
6 =>
array (
'item' => '90W ADAPTER',
'ff' => '',
'proc' => '',
'mfgr' => 'DELL',
'category' => 'ACCESSORIES',
'purchaseCost' => '$10.00',
'qty' => '1',
),
),
);
?>
in PHP how can I filter this array on 'category' => 'DESKTOPS'
only to show only DESKTOPS in the new array?
This is what I have tried:
foreach ($dummyData as $key => $desktops) {
foreach(desktops as $desktop) {
if($desktop[category] =="DESKTOPS"){
// add to new array
$DESKTOPS[] = array('item' => $desktop[item],'ff' => $desktop[ff],'proc' => $desktop[proc],'mfgr' => $desktop[mfgr],'category' => $desktop[category],'purchaseCost' => $desktop[purchaseCost],'qty' => $desktop[qty]);
}
}
}
But only returns this empty array:
Array Dump:
<?php
$data =
array (
);
?>
Use array_filter() to filter your array:
<?php
$data = array (
5 =>
array (
'item' => '600 G1',
'ff' => 'SFF',
'proc' => 'i5',
'mfgr' => 'HP',
'category' => 'DESKTOPS',
'purchaseCost' => '$56.00',
'qty' => '4',
),
6 =>
array (
'item' => '90W ADAPTER',
'ff' => '',
'proc' => '',
'mfgr' => 'DELL',
'category' => 'ACCESSORIES',
'purchaseCost' => '$10.00',
'qty' => '1',
),
);
function desktopsOnly($var) {
return $var['category'] == "DESKTOPS";
}
$arrayDesktops = array_filter($data, "desktopsOnly");
print_r($arrayDesktops);
will print out:
Array
(
[5] => Array
(
[item] => 600 G1
[ff] => SFF
[proc] => i5
[mfgr] => HP
[category] => DESKTOPS
[purchaseCost] => $56.00
[qty] => 4
)
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.