-1

sample array:

$team = array(
    array(
        "cid" => 123,
        "pid" => 000,
        .
        .
    ),
    array(
        "cid" => "666",
        "pid" => "000",
        .
        .
    ),
    array(
        "cid" => "777",
        "pid" => "123",
        .
        .
    ),
    array(
        "cid" => "888",
        "pid" => "123",
        .
        .
    ),
    array(
        "cid" => "999",
        "pid" => "777",
        . 
        .
    ),
    .
    .
);

I have a similar array with 100 Thousands of data. When I search for a data using a foreach or for loop it takes lot of time. Is there any better way to do it?

Suppose I want to find out all the cid where pid = 123.

Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25
akhil regonda
  • 159
  • 2
  • 13
  • 1
    Can you put `[ pid => [ cid1, cid2, cid3 ] ]` and use the pid as the key for accessing? – Devon Bessemer Jan 05 '18 at 13:08
  • I do not post this as an answer, because im not sure if it is faster, but you can use `$cids = array_column($array, 'pid');` to extract the column `pid` out of each inner array while keeping the indices. Then you can search on that. The search will be faster, but `array_column` will take some time aswell. – Philipp Maurer Jan 05 '18 at 13:11
  • 3
    Do you generate the whole array on each request? This seems to be data that belongs in a database so you only need to load the required data and easily could search it – rypskar Jan 05 '18 at 13:12
  • 1
    seems to me like the easiest (and probably most efficient way to do this would be to limit the amount of records being fetched (either via an SQL query or an API call). dealing with such a big array is almost always going to cause problems. – William Perron Jan 05 '18 at 13:14
  • @rypskar Nope not on each request. I actually retrieved some data from database into array, then performed some operations on it, even added few columns and then I'm searching for data. So that I can perform other operations. Search has to be performed with every 'pid'. – akhil regonda Jan 05 '18 at 13:30

1 Answers1

0

array_column and array_search If you want just one result:

$key = array_search(123, array_column($array, 'pid '));
TarangP
  • 2,711
  • 5
  • 20
  • 41