2

我需要创建一个如下所示的数组:

$va_body=array(
    "bundles" => array(
        "$table.$elem" => array("convertCodesToDisplayText" => true),
        "$table.$elem" => array("convertCodesToDisplayText" => true),
    )
);

$table是一个不会改变的字符串,$elem是从数组中提取出来的。我接近了下面的代码,但它最终只有来自$bund,的最后一个值$bund是一个有两个值的数组。我猜在每个循环中都重新声明了数组?

$va_body=array(); // declare the array outside the loop
foreach ($bund as $elem ) {
    $va_body['bundles'] = array($table.".".$elem=>array("convertCodesToDisplayText" => true));
}

$bund数组有两个元素“description”和“type_id”。

$va_body['bundles'][] // Adding [] doesn't work as it modifies the expected outcome.

print_r($va_body)看起来像这样:

Array (
    [bundles] => Array (
        [ca_objects.type_id] => Array (
            [convertCodesToDisplayText] => 1
            )
        )
    ) 

我需要它是:

Array (
    [bundles] => Array (
        [ca_objects.description] => Array (
            [convertCodesToDisplayText] => 1
        )
        [ca_objects.type_id] => Array (
            [convertCodesToDisplayText] => 1
        )
    )
)

提前致谢。

@phpisuber01 使用:

$va_body['bundles'][] = array($table.".".$elem=>array("convertCodesToDisplayText" => true));

print_r($va_body);看起来像这样:

 Array (
    [bundles] => Array (
        [0] => Array (
            [ca_objects.description] => Array (
                [convertCodesToDisplayText] => 1
            )
        )
        [1] => Array (
            [ca_objects.type_id] => Array (
                [convertCodesToDisplayText] => 1
            )
        )
    )
) 

我需要它是这样的:

Array (
    [bundles] => Array (
        [ca_objects.description] => Array (
            [convertCodesToDisplayText] => 1
        )
        [ca_objects.type_id] => Array (
            [convertCodesToDisplayText] => 1
        )
    )
)

@phpisuber01 的回答:

$va_body['bundles'][$table.".".$elem] = array("convertCodesToDisplayText" => true);

非常感谢!

4

2 回答 2

1

您需要创建一个数组数组。在您的循环中更改以下行:

$va_body['bundles'][$table.".".$elem] = array("convertCodesToDisplayText" => true);

[]之后添加$va_body['bundles']

所有这一切都是不断将新的捆绑包添加到阵列中。您的原始代码每次迭代都会覆盖捆绑包。这就是为什么你只得到最后一个。

更新以更接近 OP 的确切需求。

于 2013-06-17T19:00:22.160 回答
0
$va_body = array();
$va_body['bundles'] = array();

foreach ($bund AS $elem)
{
    $va_body['bundles']["{$table}.{$elem}"] = array("convertCodesToDisplayText" => true);
}
于 2013-06-17T19:24:00.127 回答