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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀