用php foreach中的条件打开和关闭花括号

时间:2015-10-01 10:46:24

标签: php arrays json

我在php中有一个数组,如下所示: -

  $('#seabutton').click(function()
        {
            var sea=$('#search').val();
            var cont=$('p').val();
            alert(cont);
            $('p:contains('+sea+')').each(function()
                 {
    /*          $(this).html($(this).html().replace(new RegExp(sea, 'g'),'<span class=someclass>'+sea+'</span>'));
     */            $(this).html($(this).html().replace(
                        new RegExp(sea, 'i'), '<span class=someclass>'+sea+'</span>'
                  )); 
            });

        });
        $('p').click(function()
        {
            $(".someclass").css("color", "black");
        });
        $('#search').blur(function()
        {
            $(".someclass").css("color", "black");

        });

    })


    </script>
    <style type="text/css">
    .someclass {
        color: red;
    }
    </style>
    </head>
    <body>
    <!-- Select Country:<select id="country" name="country">
    </select>
    <table id="state" border="1">


    </table> -->
    <br>
    Enter Text:<input type="text" id="search"/><input type="button" id="seabutton" value="Search"/>
    <div id="serach">
    <p>This is ankush Dapke
    </p>

    </div>
    </body>
    </html>
从这个数组

我想要下面给出的json格式数组: -

Array
(
    [0] => Array
        (
            [team1_score] => 10
            [team2_score] => 5
            [round_number] => 1
            [teamtitle1] => Chennai super kings
            [teamtitle2] => Spartans
        )

    [1] => Array
        (
            [team1_score] => 15
            [team2_score] => 10
            [round_number] => 1
            [teamtitle1] => Lions11
            [teamtitle2] => Kings Xl Punjab
        )

    [2] => Array
        (
            [team1_score] => 15
            [team2_score] => 5
            [round_number] => 1
            [teamtitle1] => Zimbabwe
            [teamtitle2] => Red Steel
        )

    [3] => Array
        (
            [team1_score] => 10
            [team2_score] => 15
            [round_number] => 2
            [teamtitle1] => Zimbabwe
            [teamtitle2] => Chennai super kings
        )

    [4] => Array
        (
            [team1_score] => 15
            [team2_score] => 7
            [round_number] => 3
            [teamtitle1] => Chennai super kings
            [teamtitle2] => Chennai super kings
        )

)

我已经尝试过了,但它的格式不合适。请帮助我,我陷入困境。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

首先,您需要修改数据结构,以便为team1和team2组合分别创建数组。将其添加到一个保持数组,然后只使用json_encode简单。

// $data is your array
$output = [];
foreach ($data as $row) {
    $output[] = [
        ['name'=>$row['teamtitle1'], 'score'=>$row['team1_score']], 
        ['name'=>$row['teamtitle2'], 'score'=>$row['team2_score']]
    ];
}

echo json_encode($output);

编辑:如评论中所述,如果你想要添加另一条记录,你只需首先找到胜利者,然后将其添加到数据集中,如下所示:

$output[] = ['name'=>'I am the Winner!', 'score'=>'99999'];
json_encode($output);