Поиск двумерный массив php

Проверяем наличие значения в многомерном массиве на PHP

Привет, друзья! Сегодня мы с вами немного поговорим о массивах. А именно о том, как осуществить по ним корректный поиск на совпадение. В одной из статей мы подробно рассмотрели все варианты поиска совпадений в одномерных массивах.

Для того чтобы вы понимали, о чем идем речь, поясню. Одномерный массив (на примере PHP) – это:

 $number = array("Один", "Два", "Три", "Четыре", "Пять", "Шесть");

А многомерный, например, двух-, – это:

 $number = array( array("Один", "Два", "Три"), array("Четыре", "Пять", "Шесть") );

Так вот, привычная функция «in_array», которая существует в PHP, не сможет обработать второй массив. Именно поэтому я поделюсь с вами готовой функцией, воспользовавшись которой, вы сможете проверить на соответствие ваши данные в многомерном массиве.

 function in_multiarray($e, $a) { $t = sizeof($a) - 1; $b = 0; while($b else { if(is_array($a[$b])) { if(in_multiarray($e, ($a[$b]))) { return true; > > > > $b++; > return false; >

Используйте ее без изменения. А это пример ее использования:

 $number = array( array("Один", "Два", "Три"), array("Четыре", "Пять", "Шесть") ); if(in_multiarray("Два", $number)) { echo "Элемент есть в массиве!"; >

Соответственно, при наличии совпадения будет выполняться нужное вам действие. В моем случае – это простой вывод сообщения.

Источник

PHP how to search multidimensional array with key and value

To handle searching a multidimensional array, you can use either the foreach statement or the array_search() function.

A PHP multidimensional array can be searched to see if it has a certain value.

Let’s see an example of performing the search. Suppose you have a multidimensional array with the following structure:

To search the array by its value, you can use the foreach statement.

You need to loop over the array and see if one of the child arrays has a specific value.

For example, suppose you want to get the array with the uid value of 111 :

 Note that the comparison operator in the code above uses triple equal === .

This means the type of compared values must be the same.

The code above will produce the following output:

 111  Nathan  29 In PHP 5.5 and above, you can also use the array_search() function combined with the array_column() function to find an array that matches a condition.

 305  Michael  30 Let’s create a custom function from the search code so that you can perform a more dynamic search based on key and value.
  1. The key you want to search
  2. The value you want the key to have
  3. The array you want to search

The function can be written as follows:

To handle a case where the specific value is not found, you need to add an if condition to the function.

You can return false or null when the $key is not found:

  Now you can use the find_array() function anytime you need to search a multidimensional array.
  The code above will produce the following output:

Now you’ve learned how to search a multidimensional array in PHP.

When you need to find an array with specific values, you only need to call the find_array() function above.

Feel free to use the function in your PHP project. 👍

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

PHP Search Multidimensional Array By key, value and return key

php search multidimensional array by key and value. Through this tutorial, you will learn how to search in multidimensional array for value and return key. And also learn how to search in multidimensional array for key and return value.

First, let us define what a multidimensional array is. A multidimensional array is an array that contains one or more arrays. Each array within the multidimensional array is referred to as a subarray or dimension. The subarrays can also contain other subarrays, which make up a multidimensional array.

For example, consider the following multidimensional array:

$fruits = array( array('name' => 'apple', 'color' => 'red', 'quantity' => 5), array('name' => 'banana', 'color' => 'yellow', 'quantity' => 3), array('name' => 'orange', 'color' => 'orange', 'quantity' => 7), );

This multidimensional array contains three subarrays, each of which represents a fruit. Each subarray has three key-value pairs, which represent the name, color, and quantity of the fruit.

PHP Search In Multidimensional Array By key, value

  • PHP Search Multidimensional Array By value and return key
  • PHP Search Multidimensional Array By key and return value
  • PHP search multidimensional array for multiple values

PHP Search Multidimensional Array By value and return key

Here’s an example code in PHP that demonstrates how to search a multidimensional array by value and return the key:

 1, 'name' => 'John', 'age' => 25), array('id' => 2, 'name' => 'Jane', 'age' => 30), array('id' => 3, 'name' => 'Bob', 'age' => 27), array('id' => 4, 'name' => 'Alice', 'age' => 35) ); // Function to search the array by value and return the key function search_multidimensional_array($array, $key, $value) < foreach ($array as $subarray_key =>$subarray) < if (isset($subarray[$key]) && $subarray[$key] == $value) < return $subarray_key; >> return false; > // Search the array for an employee with name 'Bob' $key = search_multidimensional_array($employees, 'name', 'Bob'); // Output the result if ($key !== false) < echo "Employee with name 'Bob' found at key: " . $key; >else < echo "Employee with name 'Bob' not found"; >?>

In this example, we have a multidimensional array $employees that contains information about employees. We want to search this array by the name of an employee and return the key of the subarray that contains the employee’s information.

To do this, we define a function search_multidimensional_array() that takes three arguments: the array to search, the key to search for, and the value to search for. The function loops through each subarray in the array using a foreach loop and checks if the subarray has a key that matches the search key and a value that matches the search value. If a match is found, the function returns the key of the subarray. If no match is found, the function returns false .

We then call the search_multidimensional_array() function with the $employees array, the key 'name' , and the value 'Bob' . The function searches the array for an employee with the name 'Bob' and returns the key of the subarray that contains the employee’s information.

Finally, we output the result of the search using an if statement. If the function returns a key that is not false , we output a message indicating that the employee was found and the key where the employee’s information is stored. Otherwise, we output a message indicating that the employee was not found.

PHP Search Multidimensional Array By key and return value

here’s an example of how to search a multidimensional array in PHP by a specific key and return its value:

Suppose we have an array called $users, which contains multiple arrays representing individual users, and each user array has keys such as “id”, “name”, and “email”. We want to search this array for a specific user by their ID and return their name.

$users = array( array( "id" => 1, "name" => "John Smith", "email" => "[email protected]" ), array( "id" => 2, "name" => "Jane Doe", "email" => "[email protected]" ), array( "id" => 3, "name" => "Bob Johnson", "email" => "bob@example.com" ) ); $search_id = 2; // The ID of the user we want to find foreach ($users as $user) < if ($user["id"] == $search_id) < $found_name = $user["name"]; break; >> if (isset($found_name)) < echo "The name of user ID $search_id is $found_name."; >else

In this example, we first define our $users array with three user sub-arrays. We then set $search_id to 2, the ID of the user we want to find. We then use a foreach loop to iterate over each sub-array in $users. Within the loop, we use an if statement to check if the “id” key of the current sub-array matches $search_id. If it does, we set $found_name to the value of the “name” key in that sub-array and break out of the loop. If no match is found, $found_name will not be set.

Finally, we check if $found_name is set and, if so, we echo out the name of the user we found. If $found_name is not set, we echo out a message saying the user was not found.

PHP search multidimensional array for multiple values

Here is an example of how to search a multidimensional array in PHP for multiple values:

Suppose you have a multidimensional array that contains information about various products, and you want to search for products that have both a certain category and a certain price range. The array might look like this:

$products = array( array("name" => "Product 1", "category" => "books", "price" => 10.99), array("name" => "Product 2", "category" => "books", "price" => 15.99), array("name" => "Product 3", "category" => "electronics", "price" => 29.99), array("name" => "Product 4", "category" => "electronics", "price" => 49.99), array("name" => "Product 5", "category" => "clothing", "price" => 19.99) );

To search this array for products that have both the category “books” and a price between $10 and $20, you can use the array_filter() function in combination with an anonymous function. The anonymous function will take each element of the array as an argument, and return true if the element matches the criteria, or false otherwise.

// Define the search criteria $category = "books"; $min_price = 10; $max_price = 20; // Define the search function $search_function = function($product) use ($category, $min_price, $max_price) < return ($product["category"] == $category && $product["price"] >= $min_price && $product["price"] ; // Perform the search $results = array_filter($products, $search_function); // Output the results foreach ($results as $result) < echo $result["name"] . " is in the category " . $result["category"] . " and costs $" . $result["price"] . "
"; >

This code defines the search criteria as variables, and then defines an anonymous function that takes a product as an argument and checks if it matches the criteria. The use keyword is used to pass the search criteria variables into the anonymous function.

The array_filter() function is then called with the $products array and the anonymous function as arguments. This filters the array to only contain elements that match the search criteria.

Finally, the code loops through the filtered results and outputs information about each matching product.

Note that this code will only match products that have a category of “books” and a price between $10 and $20. If you want to search for different criteria, you can simply modify the $category , $min_price , and $max_price variables, and adjust the anonymous function accordingly.

Conclusion

The fastest way to search a multidimensional array. In this tutorial, you have learned how to search in a multidimensional array by key, value, and multiple values.

Author Admin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Источник

Читайте также:  Stream sort map java
Оцените статью