简体   繁体   中英

Search associative array of arrays. How?

My question is how can I search an array built this way? Basically there may be a need to repeat the key and this is what I got so far to maybe solve this. If the price is the same for 2 different items I cannot have 2 keys with the same value.

Please feel free to improve on array layout.

$price_list = array(
  1 => array("9.99", "EA_WTRESRVD"),
  2 => array("9.99", "EA_WTRESRV")
);

Provided there will never be any duplication of the second column, you can do this:

$search = "EA_WTRESRVD"; //value to search for

$price_list = array(
  1 => array("9.99", "EA_WTRESRVD"),
  2 => array("9.99", "EA_WTRESRV")
);

$array = array_column($price_list, 0, 1);
echo $array[$search];

I would suggest that if you have a unique product code (SKU), you should use this to index your array.

$products = [
    'EA_WTRESRVD' => [
        'name'  => '...',
        'price' => 9.99,
        // ...
    ],
    'EA_WTRESRV' => [
        'name'  => '...',
        'price' => 9.99,
        // ...
    ],
];

Then you can access the price of any product by it's SKU.

$price = $products['EA_WTRESRV']['price'];

Here's one way:

<?php

$price_list = [  1 => array("9.99", "EA_WTRESRVD"),
                 2 => array("9.99", "EA_WTRESRV")];

$search = "EA_WTRESRV";


foreach ($price_list as $arr) {
  if (in_array( $search, $arr )) {
        echo $search;
  }
}

The foreach iterates over the multidimensional array whose elements are each arrays. Each array is inspected by in_array() for the search term.

However, this is not the only way. If you wish to avoid in_array(), you could also code as follows:

<?php

$price_list = [  1 => array("9.99", "EA_WTRESRVD"),
                 2 => array("9.99", "EA_WTRESRV")];

$search = "EA_WTRESRV";
$len = strlen($search);


foreach ($price_list as $arr) {
  $val = array_values($arr);

  foreach($val as $v) {
     if ( ( strpos( $v,$search )) !== false) {
        if ( strlen($v) == $len) {
             echo "$search is in the price list.\n";
        }
     }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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