I would like to search a multidimensional associative array for a specific Link value, then return a subset of all of the arrays that contain the same Category of the Link value passed to it.

How can array_search find the Link? Once I find the right Link value, how can I return just those arrays that contain the same Category as that Link? (Sample code would be very helpful as I am new to PHP.)

$aClip=array(
	array(Category => "Television",
				Link => "vid/01.swf",
				Img => "img/25.jpg",
				Title => "A Lot in Common",
	),
	array(Category => "Television",
				Link => "vid/02.swf",
				Img => "img/27.jpg",
				Title => "Sizongena",
	),
	array(Category => "Documentaries",
				Link => "vid/03.swf",
				Img => "img/31.jpg",
				Title => "African Roots of Jazz",
	), ...
};
Member Avatar for langsor

Something like this should work

<?php
$aClip = array(
  array(
    Category => "Television",
    Link => "vid/01.swf",
    Img => "img/25.jpg",
    Title => "A Lot in Common"
  ),
  array(
    Category => "Television",
    Link => "vid/02.swf",
    Img => "img/27.jpg",
    Title => "Sizongena"
  ),
  array(
    Category => "Documentaries",
    Link => "vid/03.swf",
    Img => "img/31.jpg",
    Title => "African Roots of Jazz"
  ),
  array(
    Category => "Documentaries",
    Link => "vid/01.swf",
    Img => "img/31.jpg",
    Title => "African Roots of Jazz"
  )
);

$found_arrays = find_link_array( 'vid/01.swf', $aClip );
print '<pre>';
print_r( $found_arrays );
print '</pre>';

function find_link_array ( $link_value, $value_array ) {
  $found_arrays = array();
  foreach ( $value_array as $assoc_array ){
    if ( $assoc_array['Link'] == $link_value ) {
      $category = $assoc_array['Category'];
      foreach ( $value_array as $assoc_arr ) {
        if ( $assoc_arr['Category'] == $category ) {
          $found_arrays[] = $assoc_arr;
        }
      }
      break;
    }
  }
  return $found_arrays;
}
?>

By the way, you have some syntax errors in your array...thought you should know

$aClip=array(
array(Category => "Television",
Link => "vid/01.swf",
Img => "img/25.jpg",
Title => "A Lot in Common",
),
array(Category => "Television",
Link => "vid/02.swf",
Img => "img/27.jpg",
Title => "Sizongena",
),
array(Category => "Documentaries",
Link => "vid/03.swf",
Img => "img/31.jpg",
Title => "African Roots of Jazz",
)
};

Hope this helps

That's a much more efficient way than what I was trying to do (which was loop through the entire array twice). Thanks for the sample.

Thanks also for pointing out the extra commas. There were more keys in the array; I just trimmed it down for brevity.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.