对数组进行分组并打印其值

时间:2012-12-30 20:05:10

标签: php arrays multidimensional-array grouping

$galleries = array (
    '0' => array ('post_id' => 300, 'photo_id' => 1),
    '1' => array ('post_id' => 300, 'photo_id' => 2),
    '2' => array ('post_id' => 300, 'photo_id' => 3),
    '3' => array ('post_id' => 301, 'photo_id' => 4),
    '4' => array ('post_id' => 301, 'photo_id' => 5),
    '5' => array ('post_id' => 302, 'photo_id' => 6),
    '6' => array ('post_id' => 302, 'photo_id' => 7),
    '7' => array ('post_id' => 302, 'photo_id' => 8),
    '8' => array ('post_id' => 302, 'photo_id' => 9),
    '9' => array ('post_id' => 303, 'photo_id' => 10),
    '10' => array ('post_id' => 303, 'photo_id' => 11),
    '11' => array ('post_id' => 304, 'photo_id' => 12),
)

我想将post_id分组并以HTML或PHP格式打印出来:

300 = 1,2,3
301 = 4,5
302 = 6,7,8,9
303 = 10,11
304 = 12

2 个答案:

答案 0 :(得分:1)

$galleries = array (
    '0' => array ('post_id' => 300, 'photo_id' => 1),
    '1' => array ('post_id' => 300, 'photo_id' => 2),
    '2' => array ('post_id' => 300, 'photo_id' => 3),
    '3' => array ('post_id' => 301, 'photo_id' => 4),
    '4' => array ('post_id' => 301, 'photo_id' => 5),
    '5' => array ('post_id' => 302, 'photo_id' => 6),
    '6' => array ('post_id' => 302, 'photo_id' => 7),
    '7' => array ('post_id' => 302, 'photo_id' => 8),
    '8' => array ('post_id' => 302, 'photo_id' => 9),
    '9' => array ('post_id' => 303, 'photo_id' => 10),
    '10' => array ('post_id' => 303, 'photo_id' => 11),
    '11' => array ('post_id' => 304, 'photo_id' => 12),
);
// written on the go, untested
$grouped = array();
foreach ($galleries as $gallery) {
    $grouped[$gallery['post_id']][] = $gallery['photo_id'];
}

foreach ($grouped as $key => $values) {
    echo $key . ' = ' . implode(',', $values) . "\n";
}

你是什么意思“在HTML或PHP中”?

答案 1 :(得分:1)

<?php // RAY_temp_mvetter.php
error_reporting(E_ALL ^ E_NOTICE);

$galleries = array (
    '0' => array ('post_id' => 300, 'photo_id' => 1),
    '1' => array ('post_id' => 300, 'photo_id' => 2),
    '2' => array ('post_id' => 300, 'photo_id' => 3),
    '3' => array ('post_id' => 301, 'photo_id' => 4),
    '4' => array ('post_id' => 301, 'photo_id' => 5),
    '5' => array ('post_id' => 302, 'photo_id' => 6),
    '6' => array ('post_id' => 302, 'photo_id' => 7),
    '7' => array ('post_id' => 302, 'photo_id' => 8),
    '8' => array ('post_id' => 302, 'photo_id' => 9),
    '9' => array ('post_id' => 303, 'photo_id' => 10),
    '10' => array ('post_id' => 303, 'photo_id' => 11),
    '11' => array ('post_id' => 304, 'photo_id' => 12),
)
;
/*
I want o group post_id and print it in HTML or in PHP to something like this:

300 = 1,2,3
301 = 4,5
302 = 6,7,8,9
303 = 10,11
304 = 12
*/

// COLLAPSE THE ARRAY
$old_post_id = FALSE;
foreach ($galleries as $arr)
{
    $out[$arr['post_id']] .= $arr['photo_id'] . ',';
}

// REMOVE THE TRAILING COMMAS
foreach ($out as $key => $str) $out[$key] = rtrim($str, ',');
print_r($out);