-1

I have a result of a query, which is the name of the image. I am storing the image names for every image Id in an array. Now, on the view page I am using foreach loop to display these images. The problem is I can't extract the elements(the name of the images) from this array.

My array is

Array ( [0] => Array ( [0] => Array ( [picture] => 5a3a13f237715637629.jpeg ) ) [1] => Array ( [0] => Array ( [picture] => 5a3b602654cfd527057.jpg ) ) )

I have used print_r and got this, now I want to extract only the 5a3a13f237715637629.jpeg values and display these using foreach loop on the view page. Any help is welcome.

Shantanu
  • 148
  • 3
  • 12

1 Answers1

0

The simplest way I can think of would be to json the array and then use regex to extract the filenames. You are then left with an array of filenames to loop through and display:

preg_match('/\w+.jpeg/', json_encode($array), $matches);

print_r($matches);

The benefits of doing it this way are that you don't need to know the structure of the array or go through embedded looping to find the values.

If you want do want the loop way; try this:

$array = array(
    1 => array(
        'picture' => '5a3a13f237715637629.jpeg'    
    ),
    2 => array(
        'picture' => 'fnofweofweiofniewof.jpeg'    
    )
);

print_r(search_r($array, 'picture', $results));

function search_r($array, $key, &$results) {

    if (!is_array($array)) {
        return;
    }

    if (isset($array[$key])) {
        $results[] = $array[$key];
    }

    foreach ($array as $subarray) {
        search_r($subarray, $key, $results);
    }

    return $results;
}

That will result:

Array
(
    [0] => 5a3a13f237715637629.jpeg
    [1] => fnofweofweiofniewof.jpeg
)

PS. This is an adaption of this answer

Phright
  • 179
  • 4