簡體   English   中英

過濾數組,其中鍵值等於字符串 PHP

[英]Filter array where key value equals as string with PHP

您好我正在嘗試重建一個鍵類別 = DESKTOPS 的數組。 這是我的數組的一個示例: $dummyData['data'][$counter] = array('item' => $A, 'ff' => $B, 'proc' => $C, 'mfgr' => $D, 'category' => $E, 'purchaseCost' => $F, 'qty' => $G);

我的數組看起來像這個例子:

<?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',
    ),
),
);
?>

在 PHP 中,我如何在'category' => 'DESKTOPS'上過濾這個數組,只在新數組中顯示桌面?

這是我嘗試過的:

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]);
           }

           }
}

但只返回這個空數組:

Array Dump:
<?php
$data =
array (
);
?>

使用array_filter()過濾你的數組:

<?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);

將打印出:

Array
(
    [5] => Array
        (
            [item] => 600 G1
            [ff] => SFF
            [proc] => i5
            [mfgr] => HP
            [category] => DESKTOPS
            [purchaseCost] => $56.00
            [qty] => 4
        )
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM