John Davidson

PHP get arrays from one and add to the property of another

0 comments
Message:


I have two arrays. One is taxonomies:


Array
(
[genres] => Array
(
[label] => Genres
[value] => genres
)

[movie_tags] => Array
(
[label] => Movie Tags
[value] => movie_tags
)

[portfolio_category] => Array
(
[label] => Portfolio Categories
[value] => portfolio_category
)

)

and postTypes:


Array
(
[movies] => Array
(
[0] => genres
[1] => movie_tags
)

[portfolio] => Array
(
[0] => portfolio_category
)

)

Is it possible to combine the two arrays to get something like this?


Array
(
[movies] => Array
(
[0] => Array ( [label] => Genres [value] => genres )
[1] => Array ( [label] => Movie Tags [value] => movie_tags )
)

[portfolio] => Array
(
[0] => Array ( [label] => Portfolio Categories [value] => portfolio_category )
)

)

I'm trying to add the label and value from taxonomies array into postTypes array but I'm not sure how to match the keys and combine the arrays. Is this possible with a foreach loop?



My Answer:
Array
(
[0] => Action
[1] => Comedy
[2] => Drama
)

And the other is movies:

Array
(
[0] => Array
(
[title] => The Avengers
[genre] => Action
)

[1] => Array
(
[title] => Bridesmaids
[genre] => Comedy
)

[2] => Array
(
[title] => The Shawshank Redemption
[genre] => Drama
)
)

I want to add the genre IDs from the taxonomies array to the movies array. So the final movies array should look like this:

Array
(
[0] => Array
(
[title] => The Avengers
[genre] => Action
[genre_id] => 0
)

[1] => Array
(
[title] => Bridesmaids
[genre] => Comedy
[genre_id] => 1
)

[2] => Array
(
[title] => The Shawshank Redemption
[genre] => Drama
[genre_id] => 2
)
)

Here's how you can achieve this in PHP:

php
$taxonomies = [
'genres' => ['Action', 'Comedy', 'Drama']
];

$movies = [
['title' => 'The Avengers', 'genre' => 'Action'],
['title' => 'Bridesmaids', 'genre' => 'Comedy'],
['title' => 'The Shawshank Redemption', 'genre' => 'Drama']
];

foreach ($movies as $key => $movie) {
$genre_id = array_search($movie['genre'], $taxonomies['genres']);
$movies[$key]['genre_id'] = $genre_id;
}

print_r($movies);


This code snippet will add the genre_id property to each movie in the movies array based on the index of the genre in the taxonomies array.

Rate this post

3 of 5 based on 5238 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us