php - 从foreach循环php中将信息存储在数组中

标签 php arrays loops foreach associative-array

如果我有一个这样的循环,以及一个存储信息的数组:

$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/

相关文章:

python - 所选值的总最大值

java - Java 中的最小值不起作用

php - 在 php 5.5.1/apache 2.4.6 中忽略带下划线的 header 名称

php - FOSElastica bundle : retrieving highlights for results

arrays - 在 MATLAB 中为数组提供与另一个数组相同的排序

java - 如何用不同的值替换相同的字符?

vba - 使用 Excel VBA 创建有效的退出条件时遇到问题

javascript - 什么样的数据应该被缓存?

php - Google Maps API V3 KML 图层不显示

javascript - 如何在总和不超过20的情况下递归地添加一个数字数组?