I have the following Array (decoded from JSON):
Array
(
[playerInfo] => Array
(
[hint] =>
[infoText] => Array
(
[multiLineMode] =>
[subText1] => TLC
[subText2] => Christmas Pop
[title] => Sleigh Ride
)
[isPlayingInLemur] =>
[lyrics] =>
[mainArt] => Array
(
[altText] => Album Art
[artType] => UrlArtSource
[contentType] => image/jpeg
[url] => https://images-na.sS500_.jpg
)
[mediaId] => 958d47b9:16
[miniArt] => Array
(
[altText] => Album Art
[artType] => UrlArtSource
[contentType] => image/jpeg
[url] => https://images-n._SS48_.jpg
)
[miniInfoText] => Array
(
[multiLineMode] =>
[subText1] => TLC
[subText2] => Prime Music
[title] => Sleigh Ride
)
[playbackSource] =>
[playingInLemurId] =>
[progress] => Array
(
[allowScrubbing] => 1
[locationInfo] =>
[mediaLength] => 223
[mediaProgress] => 80
[showTiming] => 1
[visible] => 1
)
[provider] => Array
(
[artOverlay] => PRIME_SASH
[fallbackMainArt] => Array
(
[altText] =>
[artType] => IconArtSource
[iconId] => music-no-art
[iconStyles] =>
)
[providerLogo] => Array
(
[altText] => Amazon Music
[artType] => IconArtSource
[iconId] => amazon-music
[iconStyles] =>
)
[providerName] => Prime Music
)
[queueId] => 958d47
[state] => PAUSED
[template] =>
[transport] => Array
(
[layoutType] => MusicTransportLayout
[lyrics] => HIDDEN
[next] => ENABLED
[playPause] => ENABLED
[previous] => ENABLED
[repeat] => ENABLED
[shuffle] => ENABLED
)
[volume] => Array
(
[muted] =>
[volume] => 40
)
)
)
I have the following foreach loop which prints every item (4) in the infoText array.
<?php
foreach ($player['playerInfo']['infoText'] as $music) {
echo $music;
}
?>
But I want to be able to print only the [title] in infoText array, [state] in the playerInfo parent array, and [volume] in the volume array. Is there an elegant way to do this? Also, since I'm using foreach, I only get the value of the pair, but I also need the key. That way I can print the specific items I need.
You may want to try a recursion function so you don't have to keep track of all those keys. I shortened your array for this example but it should work for you regardless of dimensions. Just provide the key to get the value in an array for the $searchterms argument.
function array_recursion(array $myarray, array $searchterms)
{
foreach ($myarray as $key => $value)
{
if (is_array($value)) array_recursion($value, $searchterms);
else if (in_array($key, $searchterms)) print $key . ": " . $value . "\n";
}
}
$myarray = Array(
'playerInfo' => Array(
'hint' => '',
'infoText' => Array(
'multiLineMode' => '',
'subText1' => 'TLC',
'subText2' => 'Christmas Pop',
'title' => 'Sleigh Ride'
),
'state' => 'PAUSED',
'volume' => Array(
'muted' => '',
'volume' => 40
)
)
);
array_recursion($myarray, Array('state', 'title', 'volume'));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments