php uses array_search and array_column to realize two dimensional array lookup

  • 2021-12-12 08:15:15
  • OfStack

When looking at the array function of php manual, I saw a highly praised user answer portal, and realized 2-dimensional array search by using array_search and array_column, without writing a loop by myself, thus reducing the workload.


<?php 
$userdb = array(
 0 => array(
      'uid' => 100,
      'name' => 'Sandra Shush',
      'url' => 'urlof100'
    ),
 
  1 => array(
      'uid' => 5465,
      'name' => 'Stefanie Mcmohn',
      'pic_square' => 'urlof100'
    ),
 
  2 => Array(
      'uid' => 40489,
      'name' => 'Michael',
      'pic_square' => 'urlof40489'
    )
);
 
$found_key = array_search(40489, array_column($userdb, 'uid'));
/**
  If $userdb Very large, it is recommended to use 1 Variable, avoiding calling every element when searching array_column()
 $uid = array_column($userdb, 'uid');
 $found_key = array_search(40489, $uid);
 */
var_dump($found_key);
 
 ?>

Title description:

In a 2-dimensional array, every 1 row is sorted in ascending order from left to right, and every 1 column is sorted in ascending order from top to bottom. Please complete a function, enter such a 2-dimensional array and an integer, and determine whether the array contains the integer.

Code:


<?php

function findInOneArray($target, $array){
  if(array_search($target,$array)!==false) return true; //1 , array_search () is in the thought array, and now we're going to find it in the 2 Dimension array, definitely borrow this 
  else return false; //2 , !==false The real usage of is the existing return false And there is a return representation false Array of 0 At the time of 
}

function Find($target, $array)
{
  foreach($array as $key => $val){
    if(findInOneArray($target, $val)) return true;
  }
  return false;
}


Related articles: