2014-02-28 79 views
0

我需要創建一個JSON數組中,索引1創建JSON數組索引開始1

這裏是我的代碼從網站上挑選圖片

 $image_urls = array(); 

      //get all images URLs in the content 
      foreach($get_content->find('img') as $element) 
      { 
       /* check image URL is valid and name isn't blank.gif/blank.png etc.. 
       you can also use other methods to check if image really exist */ 
       if(!preg_match('/blank.(.*)/i', $element->src) && filter_var($element->src, FILTER_VALIDATE_URL)) 
       { 
        $image_urls[] = $element->src; 

       } 
      } 

      //prepare for JSON 
      $output = array('title'=>$page_title, 'images'=>$image_urls, 'content'=> $page_body); 
      echo json_encode($output); //output JSON data 

data.images gives the array bu it starts with 0 
+0

前置一些虛擬值'$ image_urls'之前在數組中分配它。然後從索引1開始使用。 – techfoobar

+0

JavaScript中沒有這樣的數組,它以索引1開始。您可以將一個空元素放入數組中的'0'點,但該點仍然存在。 – jfriend00

回答

0

嘗試使用array_unshift

$image_urls = array_unshift($image_urls,null);//add an element at the zeroth index 
unset($image_urls[0]);//remove the zero index 
1

嘗試

$output = array(); 
$output['1'] = array('title'=>$page_title, 'images'=>$image_urls, 'content'=> $page_body); 
echo json_encode($output); //output JSON data 

輸出將是:

{"1":{"title":(*page_title*),"images":(*img_url*),"content":(*page_body*)}} 
+0

這不起作用 – user1851420

+0

我編輯了我的代碼,但上述解決方案不起作用 – user1851420

0

的單線解決IMAGE_URL陣列: -

$arr=array(1,2,3,4,5,6); 
$arr = array_combine(range(1, count($arr)), $arr); 
echo '<pre>';print_r($arr); 

輸出: 陣列

(
    [1] => 1 
    [2] => 2 
    [3] => 3 
    [4] => 4 
    [5] => 5 
    [6] => 6 
)