Created
November 18, 2016 06:56
-
-
Save hasnhasan/18a700f902f6370f964c41f686a48526 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$patterns = array( | |
'{title}' => '60: The Winds of Winter', | |
'{desc}' => 'Information for Episode 60: The Winds of Winter of Game of Thrones on HBO, featuring videos, images, synopsis and schedule.', | |
'{tags}' => 'HBO, Game of Thrones, Winter Is Coming, Clash of Kings George R.R. Martin', | |
'{image}' => 'http://i.lv3.hbo.com/assets/images/series/game-of-thrones/episodes/6/60/episode-60-1024.jpg', | |
'{source}' => 'http://www.hbo.com/game-of-thrones/episodes/6/60-60-the-winds-of-winter/index.html', | |
); | |
$imdbData = json_decode(file_get_contents('http://www.omdbapi.com/?i=tt0944947&plot=full&r=json'), true); | |
foreach ($imdbData as $key => $value) { | |
$patterns['{imdb_' . $key . '}'] = $value; | |
} | |
$testData = array( | |
'title' => '{imdb_Title} - {title}', | |
'tags' => 'Tags: {tags}', | |
'desc' => 'Desc: {desc}', | |
'image' => '<img src="{image}" alt="{title}">', | |
'source' => 'Source: {source}', | |
'extra' => array( | |
'language' => '{imdb_Language}', | |
'imdbInfo' => array( | |
'rating' => '{imdb_imdbRating}', | |
'votes' => '{imdb_imdbVotes}', | |
'metascore' => '{imdb_Metascore}', | |
), | |
'seriesInfo' => array( | |
'genre' => '{imdb_Genre}', | |
'released' => '{imdb_Released}', | |
'runtime' => '{imdb_Runtime}', | |
'cast' => array( | |
'director' => '{imdb_Director}', | |
'writer' => '{imdb_Writer}', | |
'actors' => '{imdb_Actors}', | |
), | |
), | |
), | |
); | |
/* | |
* Bad code | |
foreach ($testData as $key => $value) { | |
if (is_array($value)) { | |
foreach ($value as $parentKey => $parentValue) { | |
if (is_array($parentValue)) { | |
# ... | |
} else { | |
$parentValue = applyPatterns($patterns,$parentValue); | |
$value[$parentKey] = $parentValue; | |
} | |
} | |
} else { | |
$value = applyPatterns($patterns,$value); | |
} | |
$testData[$key] = $value; | |
} | |
echo "<pre>"; | |
print_r ($testData); | |
echo "</pre>"; | |
die; | |
*/ | |
#My Fix code | |
array_walk_recursive($testData, function (&$text) use ($patterns) { | |
$text = applyPatterns($patterns, $text); | |
}); | |
echo "<pre>"; | |
print_r($testData); | |
echo "</pre>"; | |
function applyPatterns($patterns, $text) { | |
$search = array_keys($patterns); | |
$replace = array_values($patterns); | |
return str_replace($search, $replace, $text); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment