【问题标题】:Merge 3 rows that have json value合并具有 json 值的 3 行
【发布时间】:2013-02-17 07:33:09
【问题描述】:

我在数据库表中有 3 行 json 数据,我希望它们将它们合并到一个数组中,如何解决?

第 1 行: ["11,22,13"]
第 2 行: ["48"]
第 3 行: ["53,67,70"]

我希望输出为:array(11,22,13,48,53,67,70)

我的尝试:

$result = $this->db->get_where('table',array('mainpage'=>$mp'));
    $data = array();
    foreach($result->result() as $row){
        $dv = json_decode($row->sbouy);
        $out = array();
        foreach($dv as $idx => $val){
            $out[] = $val;
        }
        echo '<pre>';
        print_r($out); // This is not what I want output
    }

在我的代码中输出是as(这不是我想要的输出):

Array
(
    [0] => 11,22,13
)
Array
(
    [0] => 48
)
Array
(
    [0] => 53,67,70
)

【问题讨论】:

    标签: php arrays json codeigniter


    【解决方案1】:

    使用这个

        $data = array();
        $out = array();
        foreach($result->result() as $row){
            $dv = json_decode($row->sbouy);
    
            foreach($dv as $idx => $val){
                $out[] = $val;
            }
    
        }
        echo '<pre>';
        print_r($out); // This is what you want :)
    

    您必须在 foreach 之外定义 $out。你甚至可以使用 array_merge

    而不是循环

    【讨论】:

    • array_merge怎么用,请举个例子?我希望输出为:array(11,22,13,48,53,67,70)
    • $out = array_merge($dv, $out);用这个代替循环
    • 但我的输出为:Array ( [0] =&gt; 53,67,70 [1] =&gt; 48 [2] =&gt; 11,22,13 ); 我的 php 代码为:foreach($result-&gt;result() as $row){ $dv = json_decode($row-&gt;subpage); $out = array_merge($dv, $out); } 我希望输出为:array(11,22,13,48,53,67,70) 如何可以修吗?
    猜你喜欢
    • 2017-12-16
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    相关资源
    最近更新 更多