Javascript 创建以索引1开头的JSON数组
我需要创建一个以索引1开头的JSON数组 这是我从网站上挑选图片的代码Javascript 创建以索引1开头的JSON数组,javascript,php,json,Javascript,Php,Json,我需要创建一个以索引1开头的JSON数组 这是我从网站上挑选图片的代码 $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
$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
尝试使用
array\u unshift
$image_urls = array_unshift($image_urls,null);//add an element at the zeroth index
unset($image_urls[0]);//remove the zero index
试一试
产出将是:
{"1":{"title":(*page_title*),"images":(*img_url*),"content":(*page_body*)}}
图像url数组的单行解决方案:-
$arr=array(1,2,3,4,5,6);
$arr = array_combine(range(1, count($arr)), $arr);
echo '<pre>';print_r($arr);
在数组中赋值之前,在
$image\u url
前面加上一些伪值。然后从索引1使用。javascript中没有以索引1开头的数组。您可以在数组中的0
点中放置一个空元素,但该点仍然存在。
$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
)