循环遍历json数组并按键值分组

时间:2015-10-12 21:49:55

标签: php json foreach key

在json_decode之后,我有以下数组:::

$json = Array ( [name] => Array ( [0] => Peter [1] => David ) [dep] => Array ( [0] => accounts [1] => sales ) [date] => Array ( [0] => 10/27/2015 [1] => 09/25/2015 ) );

如何按键对值进行分组,以便在PHP foreach循环中获得以下内容? :::

<ul>
    <li>Peter, accounts, 10/27/2015</li>
    <li>David, sales, 09/25/2015</li>
</ul>

我尝试了一个类似的foreach循环(见下文)而没有达到预期的效果,我能够打印所有关键字&amp;价值,但我无法按键对值进行分组,例如。 [1] :::

foreach($json as $row){
    foreach($row as $key=>$val){
        echo $key . ': ' . $val . '<br>';
    }
}

任何帮助都将受到赞赏:::

2 个答案:

答案 0 :(得分:2)

您可以使用以下代码对列表进行排序:

<?php
    $json = [
        "name" => ["Peter","David"],
        "dep" => ["accounts", "sales"],
        "date" => ["10/27/2015","09/25/2015"]
    ];
    $final = [];
    foreach($json as $section)
    {
        foreach($section as $key=>$info)
        {
            if(!isset($final[$key])) $final[$key] = "";
            $final[$key] .= $info . ", ";
        }
    }

    echo "<ul>";
    foreach($final as $row)
    {
        echo "<li>" . substr($row, 0, strlen($row) - 2) . "</li>"; // -2 to remove the extra ", "
    }
    echo "</ul>";
?>

结果:

<ul>
    <li>Peter, accounts, 10/27/2015</li>
    <li>David, sales, 09/25/2015</li>
</ul>

答案 1 :(得分:1)

也许尝试这样的事情:

$arrayCount = count($json['name']);

$output = '<ul>';

for($i = 0; $i < $arrayCount; $i++) {
    $output .= '<li>';
    $output .= $json['name'][$i] . ', ';
    $output .= $json['dep'][$i] . ', ';
    $output .= $json['date'][$i];
    $output .= '</li>';
}

$output .= '</ul>';

echo $output;

您最好使用这样的数组格式:

$json = 
Array( 
      Array( 
        'name' => 'Peter',
        'dep' => 'accounts',
        'date' => '10/27/2015'
      ),
      Array( 
        'name' => 'David',
        'dep' => 'accounts',
        'date' => '09/25/2015'
      )
    );

这是因为您可以创建一个更容易理解的foreach循环:

$output = '<ul>';

foreach($json as $row) {
    $output .= '<li>';
    $output .= $row['name'] . ', ';
    $output .= $row['dep'] . ', ';
    $output .= $row['date'];
    $output .= '</li>';
}

$output .= '</ul>';

echo $output;