我正在使用一个库系统,该系统输出一个由checkout id组织的PHP数组,例如:
Array (
[6912] => Array (
[name] => John Doe
[email] => johndoe@email.com
[telephone] => 55555555
[book] => Gone With the Wind
[book_id] => 410
)
[6913] => Array (
[name] => John Doe
[email] => johndoe@email.com
[telephone] => 55555555
[book] => War and Peace
[book_id] => 107
)
[6914] => Array (
[name] => John Doe
[email] => johndoe@email.com
[telephone] => 55555555
[book] => Pride and Prejudice
[book_id] => 222
)
)
合并公共值并将此数组重新排列为以下内容的最有效方法是什么:
Array (
[name] => John Doe
[email] => johndoe@email.com
[telephone] => 55555555
[checked_out] => Array (
[6912] => Array (
[book] => Gone With the Wind
[book_id] => 410
)
[6913] => Array (
[book] => War and Peace
[book_id] => 107
)
[6914] => Array (
[book] => Pride and Prejudice
[book_id] => 222
)
)
)
澄清
如果我通过user_id查询&#34; John Doe&#34;,那么这个数组就是我得到的,所以你可以假设在这个例子中名称,电子邮件和电话字段总是相同的。< / p>
到目前为止,我有两种不同的解决方案可以做到这一点,但目前我不确定哪种更有效,或者即使它产生了可衡量的差异。即使我将结帐时间限制为一年,我也不希望该数组包含超过182个项目(假设他们查看了一本书并在第二天将其退回)。我将使用这两种解决方案并选择一种对我来说更直观的解决方案。非常感谢,伙计们!
答案 0 :(得分:1)
只需在新的上面创建它,按名称,电子邮件,tel#一次,然后按结帐项目。示例:Output
$checked_out = array();
foreach ($values as $key => $value) {
// just a simple initial insertion
if(empty($checked_out)) {
$checked_out = array(
'name' => $value['name'],
'email' => $value['email'],
'telephone' => $value['telephone'],
);
}
// push checked out items
$checked_out['checked_out'][$key] = array('book' => $value['book'], 'book_id' => $value['book_id']);
}
echo '<pre>';
print_r($checked_out);
注意:我不知道使用这个函数的数组函数会更快。
答案 1 :(得分:1)
这消除了对foreach循环中每个项目的if检查。这也假设您在所有项目中只有唯一的电子邮件,姓名和电话。
$checked_out = array(
6912=>array('name'=>'John Doe', 'email'=> 'johndoe@email.com', 'telephone'=>'55555555', 'book'=>'Gone With the Wind', 'book_id' =>410),
6913=>array('name'=>'John Doe', 'email'=> 'johndoe@email.com', 'telephone'=>'55555555', 'book'=>'War and Peace', 'book_id' =>107),
6914=>array('name'=>'John Doe', 'email'=> 'johndoe@email.com', 'telephone'=>'55555555', 'book'=>'Pride and Prejudice', 'book_id' =>222)
);
$output = array();
$first_value = reset($checked_out);
$output['name']=$first_value['name'];
$output['email']=$first_value['email'];
$output['telephone']=$first_value['telephone'];
foreach ($checked_out as $key=>$value){
$output['checked_out'][$key] = array('book'=>$value['book'],'book_id'=>$value['book_id']);
}
print_r($output);
注意:不知道这是最快的方法。但这是我现在能想到的最快的。
答案 2 :(得分:0)
请使用此代码:
$data = array();
$data['name'] = 'John Doe';
$data['email'] = 'johndoe@email.com';
$data['telephone'] = 5555555555;
$data['checkout'] = array(
6912 => array(
'book' => 'Gone With the Wind',
'book_id' => 410
),
6913 => array(
'book' => 'War and Peace',
'book_id' => 107
),
6914 => array(
'book' => 'Pride and Prejudice',
'book_id' => 222
)
);