简体   繁体   English

在php中使用变量作为键名

[英]Use a variable as key name in php

I'm trying to fill an array with subarrays in a loop. 我正在尝试用循环中的子数组填充数组。 In each iteration there must be an array_push, and after the loop I want save the array. 在每次迭代中都必须有一个array_push,在循环后我想保存数组。 The array must be looks as follows: 该数组必须如下所示:

Array => (
    "pa_attribute1" => Array(
         'name' => 'pa_attribute1',
         'value' => 'value',
         'is_visible' => '1',
         'is_taxonomy' => '1'
    ),
    "pa_attribute2" => Array(
         'name' => 'pa_attribute2',
         'value' => 'value',
         'is_visible' => '1',
         'is_taxonomy' => '1'
    ),
    "pa_attribute3" => Array(
         'name' => 'pa_attribute3',
         'value' => 'value',
         'is_visible' => '1',
         'is_taxonomy' => '1'
    ),
)

The 'problem' is, that the name of key is a variable. '问题'是,key的名称是变量。 So, "pa_attribute1, "pa_attribute2" and so on, are the result of a function, and I 'don't know' the result, so I can't program all the possibilities. Is there a function available what I can use to create an new array with a variable as key? Like this? 所以,“pa_attribute1”,pa_attribute2“等等,是一个函数的结果,我不知道'结果,所以我无法编程所有的可能性。是否有一个函数可用我可以用来用变量作为键创建一个新数组?像这样?

$result = array();
for($i=0; $1 < $length; $i++){

    $value = get_attribute_name();

    $value = Array();

    array_push($result, [array]);
}

print_r($result);

You don't need array_push() , you can add elements directly: 你不需要array_push() ,你可以直接添加元素:

for($i=0; $i < $length; $i++){

    $result[get_attribute_name()] = [array];

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM