我有两个数组,一个是从POST方法生成的,另一个是来自数据库。
var self = this; self._stuff;
我希望能够使用POST数组中的键和来自Database数组的名称值来加入。
结果如下:
Post
Array
(
[browser] => Array
(
[0] => Firefox
[1] => Chrome
)
[firstname] => Array
(
[0] => John
)
[lastname] => Array
(
[0] => Doe
)
)
Database
Array
(
[0] => stdClass Object
(
[title] => Browser Name
[name] => browser
)
[1] => stdClass Object
(
[title] => First Name
[name] => firstname
)
[2] => stdClass Object
(
[title] => Last Name
[name] => lastname
)
)
从Post数组保持相同的顺序非常重要。
答案 0 :(得分:0)
试试这个:
$postArray = array(
'browser' => array('Firefox', 'Chrome'),
'firstname' => array('John'),
'lastname' => array('Doe')
);
$arrayObj1 = new StdClass();
$arrayObj1->title = 'Browser Name';
$arrayObj1->name = 'browser';
$arrayObj2 = new StdClass();
$arrayObj2->title = 'First Name';
$arrayObj2->name = 'firstname';
$arrayObj3 = new StdClass();
$arrayObj3->title = 'Last Name';
$arrayObj3->name = 'lastname';
$dbArray = array($arrayObj1, $arrayObj2);
$finalArray = array();
foreach ($dbArray AS $key => $dbObject) {
$finalArray[$key] = new StdClass();
$finalArray[$key]->title = $dbObject->title;
$finalArray[$key]->name = $dbObject->name;
if (count($postArray[$dbObject->name]) > 1) {
$finalArray[$key]->posted = $postArray[$dbObject->name];
} else {
$finalArray[$key]->posted = $postArray[$dbObject->name][0];
}
}
var_dump($finalArray);
在那里测试:http://sandbox.onlinephpfunctions.com/code/7bf0fa0fbdb086ae0cc8bb21a78261ca8c05c08e