简体   繁体   中英

PHP array Finding values based on two keys

I have an array I got from a mysql query

key1    key2     value

10      2       url_A
10      1       url_B
9       3       url_C
9       2       url_D
9       1       url_E
7       1       url_f

I want to put it into this format in html.

<ul class="main">
    <li id="10">
        <ul>
            <li>url_A</li>
            <li>url_B</li>
        </ul>
    </li>
     <li id="9">
        <ul>
            <li>url_C</li>
            <li>url_D</li>
            <li>url_E</li>
        </ul>
    </li>
    <li id="7">
        <ul>
            <li>url_F</li>
        </ul>
    </li>
</ul>

How can I use foreach() (or is there a better way) and get this done?

This is HOW I get my array now.

$result = mysql_query($sql) or die(mysql_error()); 
while($data = mysql_fetch_object($result)){
        $Items[] = array(   
            'key1' => $data->pID1,
            'key2' => $data->ID2,
            'value' => $data->urlString, 
        );
        }

You can build the array with two keys as well:

while ($data = mysql_fetch_object($result)) {
    $Items[$data->pID1][$data->ID2] = $data->urlString;
}

And then assemble the whole thing together:

echo '<ul class="main">';
foreach ($Items as $pid => $data) {
    printf('<li id="%s"><ul>', $pid);
    foreach ($data as $item) {
        printf('<li>%s</li>', htmlspecialchars($item, ENT_QUOTES, 'UTF-8'));
    }
    echo '</ul></li>';
}
echo '</ul>';

Btw, unless you're using HTML5, you shouldn't use numeric identifiers for your elements.

<?php
$arr[10][2] = "url_A";
$arr[10][1] = "url_B";
$arr[9][3] = "url_C";
$arr[9][2] = "url_D";
$arr[9][1] = "url_E";
$arr[7][1] = "url_F";

?>
<ul class="main">
<?php
foreach ($arr as $key => $val) {
    echo "<li id='$key'>\n\t<ul>";
    foreach ($val as $item_key => $item) {
        echo "\n\t<li>$item</li>";
    } 
    echo "\n\t</ul>\n</li>\n";
} 

?>
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM