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

2 回答 2

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 中”?

于 2012-12-30T20:09:35.540 回答
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);
于 2012-12-30T20:12:52.833 回答