drugs3550 2016-02-05 12:42
浏览 56
已采纳

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

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?

  • 写回答

3条回答 默认 最新

  • drrqwokuz71031449 2016-02-05 13:11
    关注

    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;
    }
    

    <kbd>eval.in demo</kbd>

    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 );
    }
    

    <kbd>eval.in demo</kbd>

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题