-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_idHTMLまたはPHPでグループ化して、次のように印刷したいと思います。

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

2 に答える 2

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 に答える
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 に答える