foreach loop - return only one record [duplicate]

2019-09-06 21:04发布

问题:

This question is an exact duplicate of:

  • Foreach loop (or do while maybe?) - Want to return only one record depending on page 2 answers

My db has two records with multiple fields (e.g. partnerName, image_url, etc). The foreach loop pasted below works perfectly, returning the two values 'partnerName' from the two records.
I now only want to return the value from the current record.

I replaced the following line: <?php foreach($this->challengenames as $k=>$challengename) { ?>

with <?php $challengename = $this->challengenames[0]; ?> and got rid of the ending php bracket. This gets rid of the loop, but I lose the index k so I get no values. Any advice on how to modify this loop to retain the index k but return only the value for the current record?

Many thanks!

<div id="defaultcontainerwrapper" class="maxwidth">
<?php foreach($this->challengenames as $k=>$challengename) { ?>
    <header>
        <h1>
            <div class="list">
                <span>Welcome to </span><?php echo $challengename['partnerName']; ?><span>'s Beat Waste Challenge!</span>
            </div>
        </h1>
    </header>
<?php } ?>
</div>

回答1:

Use following code -

<div id="defaultcontainerwrapper" class="maxwidth">
    <header>
        <h1>
            <div class="list">
                <span>Welcome to </span><?php echo $this->challengenames[0]['partnerName']; ?><span>'s Beat Waste Challenge!</span>
            </div>
        </h1>
    </header>
</div>


回答2:

What do you mean by current record? Because I assume $this->challengenames refers to the output from maybe fetchAll() in PDO, returning an array of database rows (as associative arrays). So by using $this->challengenames[0] you are getting the first row returned (based on the order set in the SQL query).

Index $k in your solution refers to 0. Anyway you're aren't even using $k within your loop o.o

If you wanna return only one row use fetch() or mysql_get_row() (not recommended) or equivalent. And your SQL query should have LIMIT 1



回答3:

$k is the key of $challengname starting with 0

foreach($this->challengenames as $key => $value) {
    $key[0] = $value['partnername'];
    $key[1]=$value['image_url'];
}


回答4:

If you want to get the latest data from you DB then i recommend you to fetch the data in descending order and retrieving only a single row as mention below

select * from <your table> orderby DESC

now you don't have to run a loop just use the 0th index to get the latest data