Home > Enterprise >  how can I get this structure?
how can I get this structure?

Time:12-21

I have to send an array via curl in this format:

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

at the moment I will write this structe manualy. But how can I get this structe from an array?

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

CodePudding user response:

This array

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

coded using the array() method would be

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

CodePudding user response:

A var_export with the short array notation is searched for. I am using a function from 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', ], ]"
  • Related