PHP:循环一个对象

时间:2012-06-12 12:32:32

标签: php arrays object foreach

对不起,如果这太明显了,但我已经太久了,现在我想不出怎么做。

我有:

$objectPerson = new Person();
$objectPerson->setName($arrayName);
$objectPerson->setLastName($arrayLastName);
$arrayPerson = array();  
$arrayPerson[] = $objectPerson;
$objectMainClass->setArrayPerson($arrayPerson);

$arrayName$arrayLastName来自$_REQUEST,每个都有两个元素:John,Jean和Smith,Taylor

稍后我将$objectMainClass存储在具有以下结构的数据库表中:

Id | Name | LastName

但是现在代码的方式,我在名字字段中存储John,Jean,在姓氏字段中存储Smith,Taylor:

Id | Name       | LastName
-------------------------------
1  | John, Jean | Smith, Taylor

我该怎么做才能获得:

Id | Name | LastName
--------------------
1  | John | Smith
2  | Jean | Taylor

...

我知道我必须在上面的代码中使用foreach,但我很困惑,我无法思考如何做到这一点。

非常感谢

2 个答案:

答案 0 :(得分:1)

我不得不修复代码中的一些错误,但这应该有效:

$arrayName = 'john,joe';
$arrayLastName = 'Smith,Shmoe';


$names = explode(",",   $arrayName);
$lastNames = explode(",", $arrayLastName);

$arrayPerson = array();  
//  I don't know how the actual array and object is used in your
// application, but based on context, I added your functionality
for ($i = 0; $i < count($names); $i++)
{
    // assuming $names and $lastNames are the same length
    $name = $names[$i];
    $lastName = $lastNames[$i];

    // act on $name and $lastname however you want
    $objectPerson = new Person();
    $objectPerson->setName($name);
    $objectPerson->setLastName($lastName);
    array_push($arrayPerson, $objectPerson);
}

$objectMainClass->setArrayPerson($arrayPerson);

答案 1 :(得分:-1)

Foreach($ object as $ key =&gt; $ value){