Last active
August 20, 2018 20:29
-
-
Save seantunwin/a0fd1bca92657fed1dbbdb2bdf19bc96 to your computer and use it in GitHub Desktop.
PHP: Search multi-dimensional array for specific key value and return another key's value from the same sub-array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Multi-dimensional Array to search through | |
| $a = [ | |
| [ | |
| 'item' => 1, | |
| 'code' => 100 | |
| ], | |
| [ | |
| 'item' => 2, | |
| 'code' => 200 | |
| ], | |
| [ | |
| 'item' => 3, | |
| 'code' => 300 | |
| ], | |
| [ | |
| 'item' => 4, | |
| 'code' => 400 | |
| ] | |
| ]; | |
| // Array to pass for our search parameters | |
| $search = [ | |
| // Key to search for with value as needle | |
| 'item' => 3 | |
| ]; | |
| // Target key we want the value for | |
| $targetKey = 'code'; | |
| // Get the target value via built-in PHP Array functions | |
| // with a Closure and binding with use() | |
| $targetValue = array_column(array_filter($a, function($x) use ($search) { | |
| if ($x[key($search)] === $search[key($search)]) { | |
| return $x; | |
| } | |
| }), $targetKey)[0]; | |
| echo $targetValue; // 300 | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment