如果我有一个这样的循环,以及一个存储信息的数组:
$itemArray = array();
foreach ($a->getDetails() as $b)
{
if ($b->getValue1() !== $b->getValue2())
{
if (!array_key_exists($b->getId(), $itemArray))
{
$itemArray[$b->getId()] = array('name' => $b->getName(), 'age' => $b->getAge());
}
$personName = $itemArray[$b->getId()]['name'];
$personAge = $itemArray[$b->getId()]['age'];
$content = ('Name is: ' . $personName . ', age is: ' . $personAge);
}
}
现在这只会为不匹配的 $b 的单个值输出一个“人”,我将如何存储不匹配的 $b 的多个值?
我基本上希望输出是这样的:
名字是:Dave,年龄是 30。
名字是:John,年龄是 40。
但现在只有一个“人”会得到输出,即使有两个实例
$b->getValue1() !== $b->getValue2()
$a->getDetails() 的示例输出:
array(1) {
[0]=>
object(PersonDetail)#322 (41) {
["collItemTemplateFieldPersonValues":protected]=>
NULL
["id":protected]=>
int(2375434)
["person_id":protected]=>
int(2184229)
["person_details_id":protected]=>
int(4563874)
["person_details_type_id":protected]=>
NULL
["name":protected]=>
string(4) "Test"
["person_namecode":protected]=>
string(9) "PERSON_ID"
["person_age":protected]=>
int(30)
最佳答案
您已经将所有需要的内容存储在数组中,您只需循环遍历 :)
$itemArray = array();
foreach ($a->getDetails() as $b) {
if ($b->getValue1() !== $b->getValue2()) {
if (!array_key_exists($b->getId(), $itemArray)) {
$itemArray[$b->getId()] = array('name' => $b->getName(), 'age' => $b->getAge());
}
}
}
if (count($itemArray) > 0) {
foreach($itemArray as $item) {
$personName = $item['name'];
$personAge = $item['age'] ;
$content = ('Name is: ' . $personName . ', age is: ' . $personAge);
}
}
关于php - 从foreach循环php中将信息存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35648370/