[英]PHP - Convert JSON string to HTML Select Option
I am trying to convert a JSON string to html <select>
options, but need to achieve all this in PHP without JS or jQuery.我正在尝试将 JSON 字符串转换为 html
<select>
选项,但需要在 PHP 没有 AF35077F9B7CZ 或 ZF5930DCB4CFDA2 的情况下实现所有这些Appreciate any help.感谢任何帮助。
Some background: the JSON result contains 2 columns, timestamp
and chapter_name
, which is used for a video to jump to the location of x
seconds via a select dropdown where the user can choose which chapter he wants to jump to.一些背景: JSON 结果包含 2 列,
timestamp
和章节名称,用于视频通过chapter_name
下拉菜单跳转到x
秒的位置,用户可以在其中选择他想要跳转到的章节。
$json_str = '{"timestamp":"0","chapter_name":"Introduction"},{"timestamp":"20","chapter_name":"Chapter 1"},{"timestamp":"40","chapter_name":"Chapter 2"},{"timestamp":"100","chapter_name":"Chapter 3"}';
$timestamps_arr = json_decode($json_str, true);
$timestamps_output = "
<label for=\"sel_timestamps\">Jump to: </label>
<select id=\"sel_timestamps\" name=\"sel_timestamps\" onchange=\"VidTimeJump()\">";
foreach($timestamps_arr as $timestamp){
echo '<option value="'.$timestamp['timestamp'].'">'.$timestamp['chapter_name'].'</option>';
}
$timestamps_output .= "
</select>";
The JSON you're using is invalid.您使用的 JSON 无效。 To make your code work you should also append your
<option>
s ( $timestamps_output.=...
) instead of echo
ing them right away.为了使您的代码正常工作,您还应该 append 您的
<option>
s( $timestamps_output.=...
)而不是立即echo
显它们。 You'll end up with a string $timestamps_output
that contains your <label>
and <select>
including your options.您最终会得到一个字符串
$timestamps_output
,其中包含您的<label>
和<select>
包括您的选项。
$json_str = '[{"timestamp":"0","chapter_name":"Introduction"},{"timestamp":"20","chapter_name":"Chapter 1"},{"timestamp":"40","chapter_name":"Chapter 2"},{"timestamp":"100","chapter_name":"Chapter 3"}]';
$timestamps_arr = json_decode($json_str, true);
$timestamps_output = "
<label for=\"sel_timestamps\">Jump to: </label>
<select id=\"sel_timestamps\" name=\"sel_timestamps\" onchange=\"VidTimeJump()\">";
foreach($timestamps_arr as $timestamp){
$timestamps_output .= '<option value="'.$timestamp['timestamp'].'">'.$timestamp['chapter_name'].'</option>';
}
$timestamps_output .= "
</select>";
Use echo $timestamps_output;
使用
echo $timestamps_output;
to output至 output
<label for="sel_timestamps">Jump to: </label>
<select id="sel_timestamps" name="sel_timestamps" onchange="VidTimeJump()"><option value="0">Introduction</option><option value="20">Chapter 1</option><option value="40">Chapter 2</option><option value="100">Chapter 3</option>
</select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.