PHP 将数组转换为适合作为数组键的序列化字符串
PHP convert array to serialized string suitable as an array key
我在 PHP 中有几个关联数组,如下所示:
$data1 = array("foo" => "one", "animal" => "mice");
$data2 = array("foo" => "two", "animal" => "cats");
....
我想创建另一个关联数组,使用之前数组的序列化值作为数组键。例如:
$newArray = array("data1's serialized key" => "someNewValue", ... );
序列化数组适合用作数组键吗?
它们是否包含任何不可接受的字符?
我是否需要对序列化的字符串做更多的事情以使其作为数组键被接受(同时仍保持其唯一性)?
Are serialized arrays suitable for being used as array keys?
是啊!据我所知,您可以使用序列化数组作为另一个数组中的键。但是我想不出任何用例。 :P
Do they contain any unacceptable characters?
否,除非您在原始数组中指定任何不可接受的字符。
Do I need to do something more to the serialized string to make it acceptable as an array key (while still keeping its uniqueness)?
没有。
因此,您的代码如下所示:
$data1 = array("foo" => "one", "animal" => "mice");
$data2 = array("foo" => "two", "animal" => "cats");
$serializedArrayKey1 = serialize($data1);
$serializedArrayKey2 = serialize($data2);
$newArray = array($serializedArrayKey1 => "Value for data1", ...);
我在 PHP 中有几个关联数组,如下所示:
$data1 = array("foo" => "one", "animal" => "mice");
$data2 = array("foo" => "two", "animal" => "cats");
....
我想创建另一个关联数组,使用之前数组的序列化值作为数组键。例如:
$newArray = array("data1's serialized key" => "someNewValue", ... );
序列化数组适合用作数组键吗?
它们是否包含任何不可接受的字符?
我是否需要对序列化的字符串做更多的事情以使其作为数组键被接受(同时仍保持其唯一性)?
Are serialized arrays suitable for being used as array keys?
是啊!据我所知,您可以使用序列化数组作为另一个数组中的键。但是我想不出任何用例。 :P
Do they contain any unacceptable characters?
否,除非您在原始数组中指定任何不可接受的字符。
Do I need to do something more to the serialized string to make it acceptable as an array key (while still keeping its uniqueness)?
没有。
因此,您的代码如下所示:
$data1 = array("foo" => "one", "animal" => "mice");
$data2 = array("foo" => "two", "animal" => "cats");
$serializedArrayKey1 = serialize($data1);
$serializedArrayKey2 = serialize($data2);
$newArray = array($serializedArrayKey1 => "Value for data1", ...);