ipel
ipel

Reputation: 1348

PHP search the parent key of a child value in a multidimensional array

I have a multidimensional array, for example:

$array[ 'ex1' ] = array( 'link', '915', '716' );
$array[ 'am2' ] = array( 'image', '37', '685' );
$array[ 'ple' ] = array( 'video', '354', '675' );

If I call $array[$ID][0] I get link, great!

If I search for link I need to get the parent key, in this case ex1

This is my current solution:

foreach( $array as $key => $value ) { 
if( in_array( 'link', $value ) ) { $ID = $key; }
}

Is there a better way to set the array or search the parent key?

EDIT:

If I change the array format in this way:

$array[] = array( 'ex1', 'link', '915', '716' );
$array[] = array( 'am2', 'image', '37', '685' );
$array[] = array( 'ple', 'video', '354', '675' );

I guess it is more easy to get the $ID with array_search( 'link', array_column( $array, 1, 0 )) but then I cannot read! for example: echo( $array[$ID][0] ) // should output link

Which is the better solution?

Upvotes: 1

Views: 2029

Answers (1)

You could use array_search like this

foreach($array as $k => $v) {
    $ind = array_search("link",$array[$k])
    if ($ind) { $ID = $k; break; } 
}

and when you are out of this loop you could retrieve "link" with $array[$ID][$ind].

The difference from you method here is that you don't get just a true or false like in in_array, but you also get the index of "link" with array_search inside your search block.

This, of course, wouldn't solve your problem when you search for a key which does not exist. Using your example,

$array[] = array( 'ex1', 'link', '915', '716' );
$array[] = array( 'am2', 'image', '37', '685' );
$array[] = array( 'ple', 'video', '354', '675' );

you'd get an error if you searched for 'alpha' using this method. The safe solution would be like

$ID = false
foreach($array as $k => $v) {
    $ind = array_search($needle,$array[$k])
    if ($ind) { $ID = $k; break; } 
}
if ($ID) {
    $element = $array[$ID][$ind]
} else {
    // The item searched for does NOT exist
}

This would search for the value in $needle in the haystack $array the way you want, I think.

Upvotes: 2

Related Questions