John Montgomery
John Montgomery

Reputation: 1965

Loop through json array and group by key values

After json_decode I have the following Array :::

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

How can I group the values by key so I get the following in a PHP foreach loop ? :::

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

I've tried a similar foreach loop ( see below ) without the desired results, I'm able to print all the key & value's but I'm not able to group values by key eg. [1] :::

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

Any assistance would be appreciated :::

Upvotes: 2

Views: 1766

Answers (2)

Qasim Asghar
Qasim Asghar

Reputation: 611

Perhaps try something like this:

$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;

You would also be better off using an array format like this:

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

This is because you can create a easier to understand foreach loop like this:

$output = '<ul>';

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

$output .= '</ul>';

echo $output;

Upvotes: 1

GGG
GGG

Reputation: 670

You could use the following code to sort the list:

<?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>";
?>

Result:

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

Upvotes: 2

Related Questions