$s = $conn->prepare($q);
$s->execute([$tagIdValue]);
$d = $s->fetchAll();
return $d;
function x($d) {
foreach ($d as $row) {
$val = $row["id"];
$cont = trimContent($row);
return $row;
}
}
我有一个查询,它返回表中的所有值,以及一个将其转换为关联数组的函数。但是只获得数组的第一行
答案 0 :(得分:1)
因为我们使用return内部循环,所以它只取第一个值并返回。
$s = $conn->prepare($q);
$s->execute([$tagIdValue]);
$d = $s->fetchAll();
return $d;
function x($d) {
$arr =[]
foreach ($d as $row) {
$val = $row["id"];
$cont = trimContent($row);
array_push($arr, $val)
}
return $arr;
}
答案 1 :(得分:1)
将您的返回内容置于循环之外,以便仅返回第一个循环
function x($d) {
foreach ($d as $row) {
$val = $row["id"];
$cont = trimContent($row);
return $row;
}
}
答案 2 :(得分:0)
因为,您正在循环中返回结果集。
因此,循环中仅返回第一行。
因为在第一次迭代中遇到return
语句,所以该函数将返回并且控制权将退出该函数。
接下来的迭代将不会遍历结果集。
我们需要在循环之前创建一个数组,
将结果追加到该数组
并返回数组。
更正的代码:
$s = $conn->prepare($q);
$s->execute([$tagIdValue]);
$d = $s->fetchAll();
return $d;
function x($d) {
$array = array();
foreach ($d as $row) {
$val = $row["id"];
$cont = trimContent($row);
$array[] = $row;
}
return $array;
}
答案 3 :(得分:0)
与其在循环内编写return,不如将其替换为数组push或数组移位功能。
循环结束后,返回从array_push / array_shift获得的最终结果。
答案 4 :(得分:-1)
您需要返回循环之外:
import { withRouter } from 'react-router';
class Footer extends React.Component {
render () {
const current_page = this.props.location.pathname;
return (
<footer>
<a href="/" className={current_page == '/' ? 'active' : ''}>Game</a>
<a href="/page" className={current_page == '/page' ? 'active' : ''}>Page</a>
<p>Current route <strong>{current_page}</strong></p>
</footer>
);
}
}
const WrappedFooter = withRouter(Footer)
ReactDOM.render(
<Router>
<div>
<h1>RactJS app</h1>
<Switch>
<Route exact path="/" component={ Game } />
<Route exact path="/page" component={ Page } />
</Switch>
<WrappedFooter></WrappedFooter>
</div>
</Router>,
document.getElementById('root')
);