如何从关联数组创建 json
how to create json from associate array
我是 PHP
的新手。所以请耐心等待。我必须从数据库中获取歌曲。我不知道如何使用 keyValuePair.
在 for 循环 中初始化关联数组并向其添加状态属性。
我要的是
{
"status" : "true" ,// It tells whether day available or not
"data": [
{
"name": "Joe Bloggs",
"id": "203403465"
},
{
"name": "Fred Bloggs",
"id": "254706567"
},
{
"name": "Barny Rubble",
"id": "453363843"
},
{
"name": "Homer Simpson",
"id": "263508546"
}
]
}
我的代码
$html = file_get_html('http://1stfold.com/taskbox/Farrukh/Zare/');
$output = array();// how to initialze it in for loop with keyValue pair
// Find all "A" tags and print their HREFs
foreach($html->find('.branded-page-v2-body a') as $e)
{
if (0 === strpos($e->href, '/watch?v'))
{
$output[] = $e->href . '<br>';
echo $e->href . '<br>';
}
}
echo json_encode($output);
提前致谢。
您可以将一个数组添加到 $output 数组,只需更改它:
$output[] = $e->href . '<br>';
为此:
$output['data'][] = array('name' => $name_value, 'id' => $id_value);
这会将数组推送到 $output['data'] 数组。
你应该在循环之前添加 "status" keyValuePair
我是 PHP
的新手。所以请耐心等待。我必须从数据库中获取歌曲。我不知道如何使用 keyValuePair.
在 for 循环 中初始化关联数组并向其添加状态属性。
我要的是
{
"status" : "true" ,// It tells whether day available or not
"data": [
{
"name": "Joe Bloggs",
"id": "203403465"
},
{
"name": "Fred Bloggs",
"id": "254706567"
},
{
"name": "Barny Rubble",
"id": "453363843"
},
{
"name": "Homer Simpson",
"id": "263508546"
}
]
}
我的代码
$html = file_get_html('http://1stfold.com/taskbox/Farrukh/Zare/');
$output = array();// how to initialze it in for loop with keyValue pair
// Find all "A" tags and print their HREFs
foreach($html->find('.branded-page-v2-body a') as $e)
{
if (0 === strpos($e->href, '/watch?v'))
{
$output[] = $e->href . '<br>';
echo $e->href . '<br>';
}
}
echo json_encode($output);
提前致谢。
您可以将一个数组添加到 $output 数组,只需更改它:
$output[] = $e->href . '<br>';
为此:
$output['data'][] = array('name' => $name_value, 'id' => $id_value);
这会将数组推送到 $output['data'] 数组。
你应该在循环之前添加 "status" keyValuePair