[英]PHP create array from two other arrays
Thats my first post here, so first of all, sorry for mistakes. 多数民众赞成在这里我的第一篇文章,所以首先,对不起。 I Cant solve some problem.
我不能解决一些问题。 I have to create an array from two other arrays :
我必须从另外两个数组创建一个数组:
Array#1: 阵列#1:
$a = array(5, 2, 3);
Array#2: 阵列#2:
$b = array(0 => array(
'key1' => '2',
'key2' => 'content2'),
(1 => array(
'key1' => '3',
'key2' => 'content3'),
(2 => array(
'key1' => '5',
'key2' => 'content1');
My output array have to be sth like that: 我的输出数组必须是这样的:
$output = array(0 => array(
'key1' => '5',
'key2' => 'content1'),
(1 => array(
'key1' => '2',
'key2' => 'content2'),
(2 => array(
'key1' => '3',
'key2' => 'content3');
And i totally dont know how to solve my problem. 而且我完全不知道如何解决我的问题。 No idea what to do.
不知道该怎么办。 I tried almost everything.
我几乎尝试了一切。 Any help?
有什么帮助吗? How to start (again)?
如何开始(再次)?
You can achieve this via foreach
loops: 您可以通过
foreach
循环实现此目的:
$a = array(5, 2, 3);
$b = array(
array('key1' => '2', 'key2' => 'content2'),
array('key1' => '3','key2' => 'content3'),
array('key1' => '5', 'key2' => 'content1')
);
$new = array();
foreach($a as $key) {
foreach($b as $item) {
if($item['key1'] == $key) {
array_push($new, $item);
}
}
}
Note 注意
Please attempt the question before posting your code. 发布代码前,请先尝试问题。
What you should be looking at is PHP's array sorting functions and creating a solution to match what you require. 您应该查看的是PHP的数组排序功能,并创建一个可满足您需求的解决方案。 Best to look at
uasort()
/ usort()
最好看看
uasort()
/ usort()
try a loop to create the new table 尝试循环创建新表
$x = array(5, 2, 3);
$y = array(0 => array(
'key1' => '2',
'key2' => 'content2'),
1 => array(
'key1' => '3',
'key2' => 'content3'),
2 => array(
'key1' => '5',
'key2' => 'content1'));
$new_arr = array();
foreach ($x as $xvalue) {
foreach ($y as $yvalue) {
if($yvalue['key1']==$xvalue) {
$new_arr[] = $yvalue;
}
}
}
var_dump($new_arr);
sandbox 沙盒
http://sandbox.onlinephpfunctions.com/code/7cd210a0282279af9dfe97395ea8eba04d9eb137 http://sandbox.onlinephpfunctions.com/code/7cd210a0282279af9dfe97395ea8eba04d9eb137
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.