通过将php数组转换为json而无法获得所需的输出

通过将php数组转换为json而无法获得所需的输出

问题描述:

I receive names and links of some files from an external website and convert it into a JSON string using the following code:

<?php

include('simple_html_dom.php');
$f = $_GET['f'];
$w = "www.something.com";
$dom = file_get_html($w);
$arr = array("file" => array());

foreach($dom->find('div[id=file_html] div[id=right_data]') as $top){

$n = $top->find('div', 0)->childNodes(0)->innertext;
$l = $top->find('div', 2)->childNodes(0)->childNodes(0)->childNodes(0)->href;
$jj[] = array('name' => $n, 'link' => $l);


}
array_push($arr['file'], $jj);

echo json_encode($arr);

?>

The output I expect is

{"songs":[{"name":"file1","link":"link1"},{"name":"file2","link":"link2"}]}

But the output i get is:

{"songs":[[{"name":"file1","link":"link1"},{"name":"file2","link":"link2"}]]}

Could someone kindly point out the error in my code? Thank you

Remove this one,

$arr = array("file" => array());

after iteration of foreach()

foreach($dom->find('div[id=file_html] div[id=right_data]') as $top){
  // as it is....
}

$arr['file'] = $jj;