多次元配列の値に基づいて要素を削除するにはどうすればよいですか?

Linda Hamilton
リリース: 2024-10-18 12:44:03
オリジナル
129 人が閲覧しました

How to Delete Elements Based on Value in a Multidimensional Array?

Deleting Elements from a Multidimensional Array Based on Value

In programming, it becomes necessary to modify arrays for various reasons. One such modification is removing elements based on a specific value. This article will guide you through deleting elements from a multidimensional array based on a value using PHP.

Here's the scenario: Consider an array containing information about films, where each sub-array represents a film and has keys like 'url', 'title', 'year', and so on. Your task is to remove any sub-array that has a 'year' key with the value 2011.

To effectively tackle this challenge, we employ the following logic:

<code class="php">function removeElementWithValue($array, $key, $value){
     foreach ($array as $subKey =&gt; $subArray) {
          if ($subArray[$key] == $value) {
               unset($array[$subKey]);
          }
     }
     return $array;
}</code>
ログイン後にコピー

This function iterates through each sub-array within the multidimensional array and checks if the specified 'key' has the desired 'value'. If a match is found, the corresponding sub-array is removed from the array.

Finally, you can call this function as follows:

<code class="php">$array = removeElementWithValue($array, "year", 2011);</code>
ログイン後にコピー

This will return a new array with all the sub-arrays containing the 'year' key set to 2011 removed, leaving you with only the sub-arrays that meet your criteria.

以上が多次元配列の値に基づいて要素を削除するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!