php更改名称以构造关联数组

时间:2022-02-02 21:19:20

Is it possible in php to change the name used to create an associative array? I am using mongo in php but it's getting confusing using array() in both cases of indexed arrays and associative arrays. I know you can do it in javascript by stealing the Array.prototype methods but can it be done in php my extending the native object? it would be much easier if it was array() and assoc() they would both create the same thing though.

是否有可能在PHP中更改用于创建关联数组的名称?我在php中使用mongo,但在索引数组和关联数组的两种情况下使用array()会让人感到困惑。我知道你可以通过窃取Array.prototype方法在javascript中完成它但是可以在php中完成我的扩展本机对象吗?如果它是array()和assoc()它们会创建相同的东西会容易得多。

EDIT -------

编辑-------

following Tristan's lead, I made this simple function to easily write in json in php. It will even take on variable from within your php as the whole thing is enclosed in quotes.

在Tristan的带领下,我创建了这个简单的函数,可以在php中轻松写入json。它甚至会从你的php中获取变量,因为整个事情都用引号括起来。

$one = 'newOne';
$json = "{
    '$one': 1,
    'two': 2
}";

// doesn't work as json_decode expects quotes.
print_r(json_decode($json));

// this does work as it replaces all the single quotes before 
// using json decode.
print_r(jsonToArray($json));

function jsonToArray($str){
    return json_decode(preg_replace('/\'/', '"', $str), true);
}

1 个解决方案

#1


1  

In PHP there is no "name used to create an associative array" or "name used to create an indexed array". PHP Arrays are ordered maps like in many other scripting languages.

在PHP中,没有“用于创建关联数组的名称”或“用于创建索引数组的名称”。 PHP数组是许多其他脚本语言中的有序映射。

This means that you can use an array whichever way you please.

这意味着您可以以任何方式使用数组。

If you wanted an indexed array..

如果你想要一个索引数组..

$indexedArray = array();

$indexedArray[] = 4; // Append a value to the array.

echo $indexedArray[0]; // Access the value at the 0th index.

Or even..

甚至..

$indexedArray = [0, 10, 12, 8];

echo $indexedArray[3]; // Outputs 8.

If you want to use non integer keys with your array, you simply specify them.

如果要对数组使用非整数键,只需指定它们即可。

$assocArray = ['foo' => 'bar'];

echo $assocArray['foo']; // Outputs bar.

#1


1  

In PHP there is no "name used to create an associative array" or "name used to create an indexed array". PHP Arrays are ordered maps like in many other scripting languages.

在PHP中,没有“用于创建关联数组的名称”或“用于创建索引数组的名称”。 PHP数组是许多其他脚本语言中的有序映射。

This means that you can use an array whichever way you please.

这意味着您可以以任何方式使用数组。

If you wanted an indexed array..

如果你想要一个索引数组..

$indexedArray = array();

$indexedArray[] = 4; // Append a value to the array.

echo $indexedArray[0]; // Access the value at the 0th index.

Or even..

甚至..

$indexedArray = [0, 10, 12, 8];

echo $indexedArray[3]; // Outputs 8.

If you want to use non integer keys with your array, you simply specify them.

如果要对数组使用非整数键,只需指定它们即可。

$assocArray = ['foo' => 'bar'];

echo $assocArray['foo']; // Outputs bar.