php 我怎样才能得到这个结构?

mjqavswn  于 2022-12-21  发布在  PHP
关注(0)|答案(2)|浏览(95)

我必须通过curl发送一个数组,格式如下:

["items"=>[[ "key1" => "value1"],[ "key2" => "value2"]]]

现在我会手工写这个结构体,但是我怎么从数组中得到这个结构体呢?

$myArray = array( "items" => array ( "key1" => "value1", "key2" => "value2"));
guicsvcw

guicsvcw1#

此阵列

["items"=>[[ "key1" => "value1"],[ "key2" => "value2"]]]

使用array()方法编码的代码将是

array( "items" => array( array( "key1" => "value1"), array("key2" => "value2")));
fhg3lkii

fhg3lkii2#

搜索带有短数组符号的var_export。我使用https://gist.github.com/Bogdaan/ffa287f77568fcbb4cffa0082e954022中的函数

function varexport($expression, $return=FALSE) {
    if (!is_array($expression)) return var_export($expression, $return);
    $export = var_export($expression, TRUE);
    $export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);
    $array = preg_split("/\r\n|\n|\r/", $export);
    $array = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [NULL, ']$1', ' => ['], $array);
    $export = join(PHP_EOL, array_filter(["["] + $array));
    if ((bool)$return) return $export; else echo $export;
}

$myArray = array( "items" => array ( "key1" => "value1", "key2" => "value2"));

$str = varexport($myArray,true);
//$str: string(88) "[ 'items' => [ 'key1' => 'value1', 'key2' => 'value2', ], ]"

相关问题