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?

Link to comment
Share on other sites

$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
        )

)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.