在循环中组合数组值

时间:2018-02-16 18:32:54

标签: php arrays json loops object

我有这样的json数据:

    {
        "no" : "",
        "hs_code" : "01.05",
        "uraian" : "Unggas hidup, yaitu ayam dari spesies Gallus",
        "description" : "Live poultry, thatis to say, fowls of the ",
        "bm" : ""
    },
    {
        "no" : "",
        "hs_code" : "",
        "uraian" : "domestic us, bebek, an gs a, kalkun dan a yam guinea",
        "description" : "species Gallus domesticus, ducks, geese,",
        "bm" : ""
    },
    {
        "no" : "",
        "hs_code" : "",
        "uraian" : "",
        "description" : "turkeys and guinea fowls",
        "bm" : ""
    },
{
        "no" : "",
        "hs_code" : 0002"",
        "uraian" : "ssss",
        "description" : "ssss",
        "bm" : ""
    },

如何在php中循环结果数据如下:

{
        "no" : "",
        "hs_code" : "01.05",
        "uraian" : "Unggas hidup, yaitu ayam dari spesies Gallus domestic us, bebek, an gs a, kalkun dan a yam guinea",
        "description" : "Live poultry, thatis to say, fowls of the species Gallus domesticus, ducks, geese turkeys and guinea fowls",
        "bm" : ""
 },
{
        "no" : "",
        "hs_code" : 0002"",
        "uraian" : "ssss",
        "description" : "ssss",
        "bm" : ""
    },

所以如果“hs_code”索引没有值,那么'uraian'和'description'索引在'uraian'和“description”索引中合并在一起,其hs_code索引有一个值,请帮助...我试试这个循环

$data =  APPPATH."modules/masterCrud/seeder/hscode_2017_tes.json";
            $sss = json_decode(file_get_contents($data));
            $result = [];
            $x = 0;
            for($i = 0; $i < count($sss); $i++)
            {
                $x--;
                $no = $sss[$i]->no;
                $hs_code = $sss[$i]->hs_code;
                if($sss[$i]->hs_code == '')
                {
                    $sss[$i]->uraian .= $sss[$i]->uraian;
                    $sss[$i]->description .= $sss[$i]->description;
                }
                $uraian = $sss[$i]->uraian;
                $description = $sss[$i]->description;
                $bm = $sss[$i]->bm;
                array_push($result,compact('no','hs_code','uraian','description','bm'));
            }
            print_r($result);

ini tidak berhasil ......

1 个答案:

答案 0 :(得分:0)

代码

$result = [];
$x= 0;
for($i = 0; $i < count($sss); $i++) {
    if($sss[$i]->hs_code) {
        $x= $i;
        $result[$i] = $sss[$i];
    } else {
        $result[$x]->uraian =  $result[$x]->uraian . ' ' . $sss[$i]->uraian;
        $result[$x]->description =  $result[$x]->description . ' ' . $sss[$i]->description;
    }
 }
array_multisort($result, SORT_ASC);
print_r($result);

解释

技巧:在每个有值的hs_code上,将该位置保存为$x $i

因此,对于空hs_code,请更新uraiandescription

$result will has difference in keys so user **array_multisort**