I am trying to extract a value from an array by searching by another value.
I have the uri
value and I require the playcount
value that corresponds with the uri.
What is the best approach to traverse this multi-level array and return the desired data?
My current code:
$decoded = json_decode($response, true);
$trackids = 'spotify:track:'. $trackid .'';
$key = array_search($trackids, array_column($decoded, 'playcount'));
$result = $decoded[$key]['playcount'];
echo "Result: ";
echo $result;
I think it is incomplete and not sure how to proceed from there as it doesn't work.
The $decoded
array:
$decoded = [
'success' => 1,
'data' => [
'uri' => 'spotify:album:3T4tUhGYeRNVUGevb0wThu',
'name' => '÷ (Deluxe)',
'cover' => [
'uri' => 'https://i.scdn.co/image/ab67616d00001e02ba5db46f4b838ef6027e6f96'
],
'year' => 2017,
'track_count' => 16,
'discs' => [
[
'number' => 1,
'name' => null,
'tracks' => [
[
'uri' => 'spotify:track:7oolFzHipTMg2nL7shhdz2',
'playcount' => 181540969,
'name' => 'Eraser',
'popularity' => 63,
'number' => 1,
'duration' => 227426,
'explicit' => null,
'playable' => 1,
'artists' => [
[
'name' => 'Ed Sheeran',
'uri' => 'spotify:artist:6eUKZXaKkcviH0Ku9w2n3V',
'image' => [
'uri' => 'https://i.scdn.co/image/ab6761610000517412a2ef08d00dd7451a6dbed6'
]
]
]
],
[
'uri' => 'spotify:track:6PCUP3dWmTjcTtXY02oFdT',
'playcount' => 966197832,
'name' => 'Castle on the Hill',
'popularity' => 79,
'number' => 2,
'duration' => 261153,
'explicit' => null,
'playable' => 1,
'artists' => [
[
'name' => 'Ed Sheeran',
'uri' => 'spotify:artist:6eUKZXaKkcviH0Ku9w2n3V',
'image' => [
'uri' => 'https://i.scdn.co/image/ab6761610000517412a2ef08d00dd7451a6dbed6'
]
]
]
]
]
]
]
]
];
My Answer:
To achieve the desired result, you can use a recursive function to search through the multidimensional array and return the playcount value corresponding to the given uri. Here's an example code snippet to accomplish this:
php
function searchPlaycountByUri($array, $uri) {
foreach ($array as $key => $value) {
if (is_array($value)) {
if (isset($value['uri']) && $value['uri'] === $uri) {
return $value['playcount'];
} else {
$result = searchPlaycountByUri($value, $uri);
if ($result !== false) {
return $result;
}
}
}
}
return false;
}
$trackid = '7oolFzHipTMg2nL7shhdz2'; // Example track id
$uri = 'spotify:track:' . $trackid;
$playcount = searchPlaycountByUri($decoded, $uri);
if ($playcount !== false) {
echo "Playcount for URI $uri: $playcount";
} else {
echo "Playcount not found for URI $uri";
}
In this code snippet, the `searchPlaycountByUri` function recursively searches through the multidimensional array for the given uri and returns the playcount value if found. You can then use this function to get the playcount value for a specific uri in your `$decoded` array.
Rate this post
4 of 5 based on 2994 votesComments