0

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

我有:

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

$arrayName并且$arrayLastName来自 a$_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,但我被卡住了,以至于我无法思考如何去做。

非常感谢

4

2 回答 2

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);
于 2012-06-12T12:42:36.650 回答
-1

Foreach($object as $key=>$value) {

于 2012-06-12T12:38:59.800 回答