Fraze Jr.
Fraze Jr.

Reputation: 143

How to search in a two dimensional array?

I have a array which looks like this:

array(500) {
[1]=>
  array(4) {
    ["name"]=>
    string(17) "Final Fantasy VII"
    ["price"]=>
    string(5) "11.69"
    ["shop"]=>
    string(4) "9507"
    ["url"]=>
    string(77) "https://de.gamespl...."
  }
[2]=> ...

and I want to check if a specified game is still remaining in this array based on price, shop, url and name. My problem now is, how can I search through the array?

Because I do not have the ID of the game, it is much more difficult because the array gets stacked up like [1] => array (4) ... [2] => .... Is there maybe a better way to stack up the array? - Does it has any advantage to store the product without the ID? - Does it accelerate the search?

Because my focus is speed/optimization and I need the fastest way to complete this search... Because I have to check 5000 games I need the fastest way.

Does anyone has an idea or can tell me which one is the fastest way and how I can search in this array?

Upvotes: 2

Views: 137

Answers (2)

sevavietl
sevavietl

Reputation: 3792

The most optimal approach, in this case, would be to use isset hash lookup instead of in_array. As the primer has O(1) (in general) and former O(n). This means that with in_array searching time will depend on the length of the array. You can read more about Big-O Complexity.

To use isset we have to apply array_map to the array. In our case, we use json_encode to create keys.

function encodeGame($game)
{
    return json_encode([
        $game["name"],
        $game["price"],
        $game["shop"],
        $game["url"],
    ]);
}

$games = array_combine(array_map('encodeGame', $games), $games);

var_dump(isset($games[encodeGame($game1)]));
var_dump(isset($games[encodeGame($game2)]));

Here is the working demo.

Upvotes: 1

Sahil Gulati
Sahil Gulati

Reputation: 15141

You can do it like this first of all getting all columns required and then search as complete array in the your data.

PHP code demo

<?php

ini_set("display_errors", 1);
$array=array(
    array(
        "name"=> "x",
        "price"=> "12000",
        "shop"=> "212121",
        "url"=> "http://www.someurl.com",
    ),
    array(
        "name"=> "xy",
        "price"=> "11000",
        "shop"=> "1212121",
        "url"=> "http://www.someotherurl.com",
    )
);
// date need to search for 
$gameName="xy";
$gamePrice="11000";
$gameURL="http://www.someotherurl.com";
$gameId="1212121";

//Creating array from data for searching.
$dataToSearch=array(
    "name"=> "xy",
    "price"=> "11000",
    "url"=> "http://www.someotherurl.com",
    "shop"=> "1212121",
);
if(in_array($dataToSearch, $array))
{
    echo "Game found!";
}

Upvotes: 1

Related Questions