Jump to content

modify multidimensional array values that meet a criterion


Cinner

Recommended Posts

Hi guys,

 

I have a multidimensional array containing movie data. One of the elements is a movie title, and for each title that starts with "The", I want to cut that part and put it at the end of the element value (like "Terminator, The"). This would be easy if I would do this during a regular foreach loop echoing all the movie titles, but what I want to do is update the array itself, since I will be doing other things with this array later. Here's an example of what my array could look like:

 

$movies = Array ( [0] => Array ( [id] => 1 [year] => 1984 [title] => The Terminator),
[1] => Array ( [id] => 2 [year] => 1994 [title] => True Lies)
);

 

The real array is a bit more complex than that but you get the picture. How do I go through it and look for "The" in the title, and put it at the end of the movie title?

$movies = Array(
0 => Array(
	'id' => 1,
	'year' => 1984, 
	'title' => 'The Terminator'
),
1 => Array(
	'id' => 2,
	'year' => 1994,
	'title' => 'True Lies'
)
);

$movies = array_map(
create_function(
	'$movie',
	'if(strtolower(substr($movie["title"], 0, 3)) == "the")
	{
		$movie["title"] = substr($movie["title"], 4) . ", " . substr($movie["title"], 0, 3);
	}
	return $movie;'
),
$movies
);

print_r($movies);

 

Output:

Array
(
    [0] => Array
        (
            [id] => 1
            [year] => 1984
            [title] => Terminator, The
        )

    [1] => Array
        (
            [id] => 2
            [year] => 1994
            [title] => True Lies
        )

)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.