Home > database >  Loop through array with wildcard for element name
Loop through array with wildcard for element name

Time:09-27

I am working a Rightmove BLM file and converting it into an array which is working fine.

However, the images are stored in sequential element nodes MEDIA_IMAGE_00, 01, 02 etc..

I am wondering if someone can advise me the best way to loop though those sequential elements using a wildcard or similar MEDIA_IMAGE_* for example.

Example of struture:

[MEDIA_IMAGE_00] => 003436_RX78401_IMG_00.jpg 
[MEDIA_IMAGE_TEXT_00] => 
[MEDIA_IMAGE_01] => 003436_RX78401_IMG_01.jpg 
[MEDIA_IMAGE_TEXT_01] => 
[MEDIA_IMAGE_02] => 003436_RX78401_IMG_02.jpg 
[MEDIA_IMAGE_TEXT_02] => 
[MEDIA_IMAGE_03] => 003436_RX78401_IMG_03.jpg

Many Thanks!

CodePudding user response:

The easiest solution might be:

foreach($array as $key=>$image)
{
   if(str_contains($key, 'MEDIA_IMAGE_'))
   {
       //$image is your filename for the current image
   }
}

But you can use RegEx instead. In this case you just change the condition of the if to something like:

preg_match('/MEDIA_IMAGE_\d\d/', $key) === 1

CodePudding user response:

You can use array_filter() in combination with an own filter-function.

Example

$inputArray['MEDIA_IMAGE_00'] = '003436_RX78401_IMG_00.jpg';
$inputArray['MEDIA_IMAGE_TEXT_00'] =  '';
$inputArray['MEDIA_IMAGE_01'] = '003436_RX78401_IMG_01.jpg';
$inputArray['MEDIA_IMAGE_TEXT_01'] = '';
$inputArray['MEDIA_IMAGE_02'] = '003436_RX78401_IMG_02.jpg';
$inputArray['MEDIA_IMAGE_TEXT_02'] = '';
$inputArray['MEDIA_IMAGE_03'] = '003436_RX78401_IMG_03.jpg';

var_dump($inputArray);

/*
array(7) {
  ["MEDIA_IMAGE_00"]=>
  string(25) "003436_RX78401_IMG_00.jpg"
  ["MEDIA_IMAGE_TEXT_00"]=>
  string(0) ""
  ["MEDIA_IMAGE_01"]=>
  string(25) "003436_RX78401_IMG_01.jpg"
  ["MEDIA_IMAGE_TEXT_01"]=>
  string(0) ""
  ["MEDIA_IMAGE_02"]=>
  string(25) "003436_RX78401_IMG_02.jpg"
  ["MEDIA_IMAGE_TEXT_02"]=>
  string(0) ""
  ["MEDIA_IMAGE_03"]=>
  string(25) "003436_RX78401_IMG_03.jpg"
}
*/

$inputArray = array_filter($inputArray, function($key) {
    return preg_match('/MEDIA_IMAGE_\d\d/', $key) === 1;
}, ARRAY_FILTER_USE_KEY);

var_dump($inputArray);
/*
array(4) {
  ["MEDIA_IMAGE_00"]=>
  string(25) "003436_RX78401_IMG_00.jpg"
  ["MEDIA_IMAGE_01"]=>
  string(25) "003436_RX78401_IMG_01.jpg"
  ["MEDIA_IMAGE_02"]=>
  string(25) "003436_RX78401_IMG_02.jpg"
  ["MEDIA_IMAGE_03"]=>
  string(25) "003436_RX78401_IMG_03.jpg"
}
*/

If you just want to filter out empty values, you can even use filter_array() without any custom function. See the documentation for more information.

Documentation

array_filter() in php documentation.

  • Related