我有一个工作数组如下
"content" => array
(
array //sub array for image 1
(
'url' => $uploadspath.$media_url0,//main image
"type" =>$type0,//media type
"caption"=>$caption0
),
array //sub array for image 2
(
'url' => $uploadspath.$media_url1,//main image
"type" =>$type1,//media type
"caption"=>$caption1
),
array //sub array for image 3
(
'url' => $uploadspath.$media_url2,//main image
"type" =>$type2,//media type
"caption"=>$caption2
),
....Programatically add new sub arrays here subject to the existence of $media_url(4,5,6 etc)..
);
我从数据库中获取$media_url
和其他数据。如果有$media_url4;
$media_url5;
$media_url6;
$media_url7;
等值,我想通过添加额外的子数组和相关的URL /类型/标题元素来编程扩展数组。 。(最多10张图片)
我的问题是如何使用额外的子数组来编码我的数组的扩展,纯粹基于其他media_urls的存在。简单地说,我希望能够按照以下几行做一些事情,但我不知道如何在嵌套数组结构中实现它...
if ($media_url4) {code to add sub array/element for image 4}
if ($media_url5) {code to add sub array/elementsfor image 5}
etc...
感谢您的帮助。
答案 0 :(得分:0)
//Below we have a function or pdo function that return the new values from database that you want to put in the CONTENT MASTER ARRAY, NOW we put the values in a variable $rows
$rows = functionThatReturnNewValuesToPutInContentArray();
//The foreach looping the variable rows, getting each row in database and putting this in a variable $row
foreach($rows as $row){
//If the $row object data from database contains media_url value add new subarray to masterContentArray
if($row->media_url != ''){
$newSubArray = [
//$row->media_url, is considering that you have a column in your db named by media_url, and that contains url string
'url'=>$row->uploadsPath . $row->media_url,
'type'=>$row->type,
'caption'=>$row->caption,
];
array_push($masterContentArray['content'], $newSubArray);
}
}
return json_encode($content);