在自定义字符串布局中转换数组索引?

I have an array called $context with this structure:

array(2) {
[0]=>
 array(2) {
  ["name"]=>
  string(6) "Foo"
  ["username"]=>
  string(6) "Test"
}
[1]=>
array(2) {
["name"]=>
string(4) "John"
["username"]=>
string(3) "Doe"
 }
}

I want convert it into this string:

string 1:

0: array(
   'name' => 'Foo',
   'username' => 'Test',
)

string 2:

1: array(
   'name' => 'John',
   'username' => 'Doe',
) 

How you can see I want save the current index in the iteration and display the array content formatted as 'name' and 'username' in a single line. I already tried with this code:

    $export = '';

    foreach($context as $key => $value)
    {
        $export .= "{$key}: ";
        print_r($value);
        $export .= preg_replace(array(
            '/=>\s+([a-zA-Z])/im',
            '/array\(\s+\)/im',
            '/^  |\G  /m'
        ), array(
            '=> $1',
            'array()',
            '    '
        ), str_replace('array (', 'array(', var_export($value, true)));

        print_r($export);

        $export .= PHP_EOL;
    }

    return str_replace(array('\\\\', '\\\''), array('\\', '\''), rtrim($export));

but I'm looking for a more optimized solution, any suggest?

This is my code:

$context = [['name'=>'Foo','username'=>'Test'],['name'=>'John','username'=>'Doe']];
$schema = "   '%s' => '%s'";
$lineBreak = PHP_EOL;

foreach( $context as $idx => $array )
{
    $lines = array();
    foreach( $array as $key => $val )
    {
        $lines[] = sprintf( $schema, $key, $val );
    }
    $output = "{$idx}: array({$lineBreak}".implode( ",{$lineBreak}", $lines )."{$lineBreak})";
    echo $output.$lineBreak;
}

eval.in demo

It will works independently from the number of elements in sub-arrays

I have used classic built-in function sprintf to format each array row: see more.

You can change $lineBreak with you preferred endLine character; In the above example, each string is printed, but (you have a return in your function, so i think inside a function), you can modify in this way:

$output = array();
foreach( $context as $idx => $array )
{
    (...)
    $output[] = "{$idx}: array({$lineBreak}".implode( ",{$lineBreak}", $lines )."{$lineBreak})";
}

to have an array filled with formatted string.

You can easly transform it in a function:

function contextToString( $context, $schema=Null, $lineBreak=PHP_EOL )
{
    if( !$schema ) $schema = "   '%s' => '%s'";
    $output = array();

    foreach( $context as $idx => $array )
    {
        $lines = array();
        foreach( $array as $key => $val )
        {
            $lines[] = sprintf( $schema, $key, $val );
        }
        $output[] = "{$idx}: array({$lineBreak}".implode( ",{$lineBreak}", $lines )."{$lineBreak})";
    }

    return implode( $lineBreak, $output );
}

eval.in demo

to change each time the schema and the line break.

PS: I see that in you code there is a comma also at the end of the last element of eache array; thinking it was a typo, I have omitted it


Edit: I have forgot the comma, added-it.
Edit 2: Added complete function example.
Edit 3: Added link to sprintf PHP page

Try this with personnal toString

$a = array(array("name"=>"Foo", "username"=>"Test"), array("name"=>"John", "username"=>"Doe"));

function toString($array){
    $s = ""; $i=0;
    foreach ($array as $key => $value) {
        $s.= $key."=>".$value;
        if($i < count($array)-1)
            $s.=",";
        $i++;
    }
    return $s;
}
$result = array();
$index = 0;

foreach ($a as $value) {
    array_push($result, $index. " : array(" . toString($value).")");
    $index ++;
}

var_dump($result);

And the result :

array (size=2)
  0 => string '0 : array(name=>Foo,username=>Test)' (length=35)
  1 => string '1 : array(name=>John,username=>Doe)' (length=35)

The result is in an array but you can change and make what you want

But you can also use json_encode :

$result = array();
$index = 0;

foreach ($a as $value) {
    array_push($result, $index. " : array(" . json_encode($value).")");
    $index ++;
}

var_dump($result);

With this result :

array (size=2)
 0 => string '0 : array({"name":"Foo","username":"Test"})' (length=43)
 1 => string '1 : array({"name":"John","username":"Doe"})' (length=43)

Simplified solution with strrpos,substr_replace and var_export:

$arr = [
    array(
    'name' => 'John',
    'username' => 'Doe'
    ),
    array(
    'name' => 'Mike',
    'username' => 'Tyson'
    )
];

/*****************/
$strings = [];
foreach($arr as $k => $v){
    $dump = var_export($v, true);
    $last_comma_pos = strrpos($dump,",");
    $cleared_value = substr_replace($dump, "", $last_comma_pos, 1);
    $strings[] = $k.": ".$cleared_value;
}
/*****************/

// Now $strings variable contains all the needed strings
echo "<pre>";
foreach($strings as $str){
    echo $str . "
";
}

// the output:
0: array (
  'name' => 'John',
  'username' => 'Doe'
)
1: array (
  'name' => 'Mike',
  'username' => 'Tyson'
)