Skip to content
Advertisement

Convert each array value into json using php

I have a PHP code that dumps following array:

array(4) { 
[0]=> string(79) "https://95.217.21.141/hls/2f04510c8f646cb3e03d5c063b190bd1611847725589-0.m3u8 " 
[1]=> string(79) "https://95.217.21.141/hls/2f04510c8f646cb3e03d5c063b190bd1611847725589-1.m3u8 " 
[2]=> string(79) "https://95.217.21.141/hls/2f04510c8f646cb3e03d5c063b190bd1611847725589-2.m3u8 " 
[3]=> string(78) "https://95.217.21.141/hls/2f04510c8f646cb3e03d5c063b190bd1611847725589-3.m3u8" 
}

I want to extract each URL from above array and convert it to JSON. JSON might look like:

{"m3u8_1":"https://95.217.21.141/hls/2f04510c8f646cb3e03d5c063b190bd1611847725589-0.m3u8","m3u8_2":"https://95.217.21.141/hls/2f04510c8f646cb3e03d5c063b190bd1611847725589-1.m3u8","m3u8_3":"https://95.217.21.141/hls/2f04510c8f646cb3e03d5c063b190bd1611847725589-2.m3u8","m3u8_4":"https://95.217.21.141/hls/2f04510c8f646cb3e03d5c063b190bd1611847725589-3.m3u8"}

I don’t know how to convert it into JSON. Also the tricky thing here is, that not every time there would be 4 URLS in array. It might be 1 or 2 or even 5. How do I check that how many URL does array has and then convert it to JSON according to that.

Also I tried searching on stack overflow before putting it here, but I didn’t found one that checks and then convert it to JSON

Thanks!

Edit #1

Direct json_encode won’t work because PHP does not return values from json which has characters such as 0 1 2 3

Advertisement

Answer

This would do the trick:

$input = [
    "https://95.217.21.141/hls/2f04510c8f646cb3e03d5c063b190bd1611847725589-0.m3u8",
    "https://95.217.21.141/hls/2f04510c8f646cb3e03d5c063b190bd1611847725589-1.m3u8",
     "https://95.217.21.141/hls/2f04510c8f646cb3e03d5c063b190bd1611847725589-2.m3u8",
     "https://95.217.21.141/hls/2f04510c8f646cb3e03d5c063b190bd1611847725589-3.m3u8"
];
$output = [];
$i = 1;
foreach($input as  $url) {
    $output['m3u8_' . $i] = $url;
    $i++;
}
print(json_encode($output));
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement