简体   繁体   English

如何在PHP中使用特定键过滤关联数组?

[英]How to filter associative array with specific key in PHP?

I'm a newbie in programming. 我是编程的新手。 Could anyone please help me with this problem? 有人可以帮我解决这个问题吗?

After print_r($product) I can get followings: (Sorry for the messy format) print_r($product)我可以得到以下信息:(对不起,格式混乱)

Array ( [product_id] => 1 [sku] => BGM0430 [set] => 9 [type] => simple [categories] => Array ( [0] => 3 [1] => 11 [2] => 14 ) [websites] => Array ( [0] => 1 ) [type_id] => simple [name] => Magical Melody Birthday Card [brand] => 3 [card_number] => XW3M0430 [assortment] => BALASST113 [old_id] => [description] =>
Presidential blue is the background for this happy birthday greeting. A delightful bouquet of multicolored balloons stretches up swirling and dodging little golden stars. "Happy Birthday" is written in large cursive across the front of the card. The message continues at the bottom of the card and says, "To You Happy Birthday." Additional golden foiled stars appear at the sides of the card.

[short_description] =>
Presidential blue is the background for this happy birthday greeting. A delightful bouquet of multicolored balloons stretches up swirling and dodging little golden stars. "Happy Birthday" is written in large cursive across the front of the card. The message continues at the bottom of the card and says, "To You Happy Birthday." Additional golden foiled stars appear at the sides of the card.


Message: Wishing you all the best on this wonderful day and throughout the year ahead.
[verse] => Wishing you all the best on this wonderful day and throughout the year ahead. [card_size] => 7 7/8 x 5 5/8 [card_stock] => 10pt C1S Envirocote 10% PCW LS2467 [url_path] => magical-melody.html [envelope] => Gold Lined White [weight] => 0.0000 [category_ids] => Array ( [0] => 3 [1] => 11 [2] => 14 ) [news_from_date] => [required_options] => 1 [news_to_date] => [has_options] => 1 [status] => 1 [image_label] => Magical Melody Birthday Card, Front [url_key] => magical-melody [visibility] => 4 [small_image_label] => Magical Melody Birthday Card, Front [country_of_manufacture] => [thumbnail_label] => Magical Melody Birthday Card, Front [promotion] => 1 [created_at] => 2013-04-05 17:17:25 [updated_at] => 2013-05-30 15:58:50 [price] => 4.0000 [group_price] => Array ( ) [special_price] => [special_from_date] => [special_to_date] => [tier_price] => Array ( ) [msrp_enabled] => 2 [minimal_price] => [msrp_display_actual_price_type] => 4 [msrp] => [enable_googlecheckout] => 1 [tax_class_id] => 2 [meta_title] => [meta_keyword] => [meta_description] => [is_recurring] => 0 [recurring_profile] => [custom_design] => [custom_design_from] => [custom_design_to] => [custom_layout_update] => [page_layout] => [options_container] => container1 [gift_message_available] => ) Array ( [product_id] => 2 [sku] => BBC23567 [set] => 9 [type] => simple [categories] => Array ( [0] => 6 ) [websites] => Array ( [0] => 1 ) [type_id] => simple [name] => Faint Flourish Anniversary Card [brand] => 3 [card_number] => [assortment] => EAASST613 [old_id] => [description] => This beautiful anniversary card with elegant flourish design is a wonderful way to recognize employees for their years of hard work. [short_description] =>
This beautiful anniversary card with elegant flourish design is a wonderful way to recognize employees for their years of hard work.
Message: Thank you for your hard work and dedication to the team!

[verse] => Thank you for your hard work and dedication to the team! [card_size] => 8 x 4 11/16 [card_stock] => 100lb 30 % PCW [url_path] => faint-flourish-anniversary-card.html [envelope] => plain white envelope [weight] => 0.0000 [category_ids] => Array ( [0] => 6 ) [news_from_date] => 2013-04-05 00:00:00 [required_options] => 1 [news_to_date] => 2013-04-30 00:00:00 [has_options] => 1 [status] => 1 [image_label] => Faint Flourish Anniversary Card - Front [url_key] => faint-flourish-anniversary-card [visibility] => 4 [small_image_label] => Faint Flourish Anniversary Card - Front [country_of_manufacture] => [thumbnail_label] => Faint Flourish Anniversary Card - Front [promotion] => 0 [created_at] => 2013-04-06 05:47:24 [updated_at] => 2013-05-30 15:34:58 [price] => 4.0000 [group_price] => Array ( ) [special_price] => [special_from_date] => [special_to_date] => [tier_price] => Array ( ) [msrp_enabled] => 2 [minimal_price] => [msrp_display_actual_price_type] => 4 [msrp] => [enable_googlecheckout] => 1 [tax_class_id] => 2 [meta_title] => [meta_keyword] => [meta_description] => [is_recurring] => 0 [recurring_profile] => [custom_design] => [custom_design_from] => [custom_design_to] => [custom_layout_update] => [page_layout] => [options_container] => container1 [gift_message_available] => ) Array ( [product_id] => 3 [sku] => BBC23576 [set] => 9 [type] => simple [categories] => Array ( [0] => 10 ) [websites] => Array ( [0] => 1 ) [type_id] => simple [name] => Faint Flourish Get Well [brand] => 3 [card_number] => [assortment] => EAASST613 [old_id] => [description] => This beautiful get well card with elegant flourish design is a wonderful way to share your hopes for a healthier tomorrow. [short_description] =>
This beautiful get well card with elegant flourish design is a wonderful way to share your hopes for a healthier tomorrow.
Message: Sending many warm thoughts and good wishes.

[verse] => Sending many warm thoughts and good wishes. [card_size] => 8 x 4 11/16 [card_stock] => 100lb 30 % PCW [url_path] => faint-flourish-get-well.html [envelope] => plain white envelope [weight] => 0.0000 [category_ids] => Array ( [0] => 10 ) [news_from_date] => 2013-04-05 00:00:00 [required_options] => 1 [news_to_date] => 2013-04-30 00:00:00 [has_options] => 1 [status] => 1 [image_label] => Faint Flouish Get Well Card - Front [url_key] => faint-flourish-get-well [visibility] => 4 [small_image_label] => Faint Flouish Get Well Card - Front [country_of_manufacture] => [thumbnail_label] => Faint Flouish Get Well Card - Front [promotion] => 0 [created_at] => 2013-04-06 05:47:24 [updated_at] => 2013-05-07 22:32:09 [price] => 4.0000 [group_price] => Array ( ) [special_price] => [special_from_date] => [special_to_date] => [tier_price] => Array ( ) [msrp_enabled] => 2 [minimal_price] => [msrp_display_actual_price_type] => 4 [msrp] => [enable_googlecheckout] => 1 [tax_class_id] => 2 [meta_title] => [meta_keyword] => [meta_description] => [is_recurring] => 0 [recurring_profile] => [custom_design] => [custom_design_from] => [custom_design_to] => [custom_layout_update] => [page_layout] => [options_container] => container1 [gift_message_available] => ) 

Data stored in $product and how can I remove other key-value pairs except when the key equals 'sku', 'name', 'price' and 'short_description' which are the information I only want to keep. $product存储的数据以及如何删除其他键值对,除非键等于“ sku”,“ name”,“ price”和“ short_description”(这是我只想保留的信息)。

The following snippet doesn't work. 以下代码段无效。

foreach($product as $key => $value){
    if($key != 'sku' || $key !='name' || $key != 'price' || $key !='short_description'){
        unset($product[$key]);
    }
}
var_dump($product);

Please let me know how can I fix this and please forgive me if I asked a stupid question. 请让我知道如何解决此问题,如果我提出了一个愚蠢的问题,请原谅我。

Any reply or help will be greatly appreciated. 任何答复或帮助将不胜感激。 Thank you so much in advance. 提前非常感谢您。

The boolean logic of that snippet is wrong, as the condition in the if statement will always be true. 该代码段的布尔逻辑是错误的,因为if语句中的条件将始终为true。 Instead use the && operator: 而是使用&&运算符:

    if($key != 'sku' && $key !='name' && $key != 'price'
                     && $key !='short_description'){

You could use the in_array function to make the condition a bit shorter: 您可以使用in_array函数使条件变短:

if (!in_array($key, ['sku','name','price','short_description']) {

In your code, if condition will be true when any one is not equal. 在您的代码中,如果条件不成立,则条件为true。 For that you can use switch 为此,您可以使用开关

foreach($product as $key => $value){
        switch($key){
         case 'sku':
         case 'name':
         case 'price':
         case 'short_description':
         break;

         default:
         unset($product[$key]);
        }
}

In above code, if the any of the key match with the case then it will skip, else if not match with any of the case, it will go to default case and remove it. 在上面的代码中,如果任何键与大小写匹配,则将跳过,否则,如果与任何大小写都不匹配,则将转到默认大小写并将其删除。

An easier to maintain workflow would be to have the keys you want stored in an array of its own and verify each key against that. 易于维护的工作流程是将要存储的密钥单独存储在一个数组中,并对照每个密钥进行验证。

$preserve = ['sku', 'name', 'price', 'short_description'];

foreach($product as $key => $value){
    if (!in_array($preserve, $key) {
        unset($product[$key]);
    }
}

Then again, this works if you never - ever - need the other values in the flow of the application, as unset will remove them from the array and cannot be restored (unless you have made a copy of it somewhere). 再说一次,如果您永远不需要应用程序流程中的其他值,这将起作用,因为unset会将它们从数组中删除并且无法恢复(除非您在某个地方进行了复制)。

You seem to want to "shape" the product into a more usable format, which can also be done "the other way around", by creating a new array/object containing only the desired keys. 您似乎想将产品“成形”为更可用的格式,也可以通过创建仅包含所需键的新数组/对象来“另一种方式”完成。

$preserve.    = ['sku', 'name', 'price', 'short_description'];
$cleanProduct = [];

foreach ($preserve as $key) {
  $cleanProduct[$key] = $product[$key];
}

This is a rather naive approach, as it will nag about keys which don't actually exist in $product , we can fix that in different ways 这是一种非常幼稚的方法,因为它会讨论$product实际上不存在的键,我们可以用不同的方式来解决它

Only use keys which actually exist 仅使用实际存在的密钥

$preserve.    = ['sku', 'name', 'price', 'short_description'];
$cleanProduct = [];

foreach ($preserve as $key) {
  //  test if the product has the key.
  if (isset($product[$key]) {
    $cleanProduct[$key] = $product[$key];
  }
}

Or by assigning a null value for keys which are not in $product , so you ensure all the keys exist but have not actual (significant) value 或通过为$product中没有的键分配空值,以确保所有键都存在但不具有实际(有效)值

$preserve.    = ['sku', 'name', 'price', 'short_description'];
$cleanProduct = [];

foreach ($preserve as $key) {
  //  always assign a value, the $product[$key] if it exists, null otherwise
  $cleanProduct[$key] = isset($product[$key]) ? $product[$key] : null;
}

Recent versions of PHP (7+) also support a shorthand version of the assignment: 最新版本的PHP(7+)也支持分配的简写形式:

$cleanProduct[$key] = $product[$key] ?? null $cleanProduct[$key] = $product[$key] ?? null ; $cleanProduct[$key] = $product[$key] ?? null ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM