Php 用子数组编程扩展数组

Php 用子数组编程扩展数组,php,arrays,dynamic-arrays,Php,Arrays,Dynamic Arrays,我有一个工作数组,如下所示 "content" => array ( array //sub array for image 1 ( 'url' => $uploadspath.$media_url0,//main image "type" =>$type0,//media type "caption"=>$caption0 ),

我有一个工作数组,如下所示

 "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\u url
和其他数据。如果
$media\u url4有值,我也希望通过添加额外的子数组和相关的URL/type/caption元素,以编程方式扩展数组
$media\u url5
$media\u url6
$media\u url7等(最多10张图像)

我的问题是,如何纯粹基于附加媒体URL的存在,用附加子数组对数组的扩展进行编码。简单地说,我希望能够沿着下面的思路做一些事情,但我不知道如何在嵌套数组结构中实现它

    if ($media_url4) {code to add sub array/element for image 4}
    if ($media_url5) {code to add sub array/elementsfor image 5}
    etc...

感谢您的帮助。

媒体url、类型和标题来自数据库,对吗?查询结果变量在哪里?请不要喊。是的,所有数据都来自数据库。该数组是json编码的,并被卷曲到第三方API。因此,我使用的数组格式是预先确定的。我刚刚扩展了我的问题以澄清API的响应是什么?只有结构还是结构和数据?媒体url来自api?嗨,拉蒙-谢谢你。我问题中的代码片段显示了一个数组的元素,该数组包含数百个额外(但更简单)元素。因此,json编码应用于从数据库查询生成的整个php数组。因此,尝试匹配您的代码片段是行不通的。我首先需要生成整个php数组。然后对其进行编码。希望这是有意义的。顺便提一下,这些图片都在我的服务器上。因此,第三方API从我的代码中获取url并调用图像。我扩展了clarityUploadsPath的问题,媒体、类型和标题来自您的数据库,好吗?您希望将查询结果的每一行放入子数组并将其推入内容数组,对吗?然后对数组进行编码,并将其返回给API,然后接收它。内容数组是一个更大的(主)数组的一部分,该数组包含数百个其他数据项,这些数据项也都来自数据库。因此,一旦数组正确格式化,我将对整个php数组进行编码。我唯一的问题是在内容数组中以编程方式生成子数组-取决于从数据库中提取的图像url的数量。我刚刚考虑的一种方法是在内容数组中手动创建(比如)10个子数组,然后如果子数组没有相关联的$media\u url,则取消设置每个子数组。不过这只是个早期的想法。我不确定它会成功。
//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);