简体   繁体   中英

Find key of a multi-dimensional associative array by value in php

I am trying to find the key of a multi-dimensional array using array functions (without looping the entire array set).

My array is like below,

$main_array = [];

$main_array[0]['id']=1001;
$main_array[0]['name']=test1;
$main_array[1]['id']=1002;
$main_array[1]['name']=test2;
$main_array[2]['id']=1001;
$main_array[2]['name']=test3;

I want to get the index of array by using the value without looping all the array (because my array is bit huge).

If I pass the value "1001", I want the two index 0 and 2. Tried with array_search() function, not working in my case.

Please help me to solve this issue.

I dont think you could avoid completely from searching the array.

your structure is not planned well. you should have used the id (which should be unique) as keys for your array like so:

$main_array[1001]['name'] = 'foo'

this would be much easier to handle and to maintain.

I suggest you to make an effort and change your structure before it gets really big.

You should consider changing structure of array . As your ID is not unique, elements with same ID stay in one array .

$main_array = array(
    1001 => array(
        array('name' => 'test1'),
        array('name' => 'test3'),
    ),
    1002 => array(
        array('name' => 'test2'),
    )
);

So

print_r( $main_array[1001] );

would give you

Array
(
    [0] => Array
        (
            [name] => test1
        )

    [1] => Array
        (
            [name] => test3
        )

)

If this is not possible, you have to loop over the entire array to achieve this.

function arraySearchId( $id, $array ) {
    $results = array();
    foreach ( $array as $key => $val ) {
        if ( $val['id'] === $id ) {
            $results[] = $key;
        }
    }
    return $results;
}

echo '<pre>';
print_r( arraySearchId( 1001, $main_array ) );
echo '</pre>';

Result:

Array
(
    [0] => 0
    [1] => 2
)

As your code

$main_array = [];
$main_array[0]['id']=1001;
$main_array[0]['name']=test1;
$main_array[1]['id']=1002;
$main_array[1]['name']=test2;
$main_array[2]['id']=1001;
$main_array[2]['name']=test3;

You require "Without looping", and the answer is: You must loop it at least once, to pre-process the data, make an indexed array.

$indexed = array();
foreach($main_array as $i=>$item) {
    if( !isset($indexed[$item['id']]) ) $indexed[$item['id']] = array();
    $indexed[$item['id']][] = $i;
}

When you need to find 1001, just

$result = $indexed['1001'] // array(0,2)

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