使用array_map使用PHP多维数组更改键 [英] Changing keys using array_map on multidimensional arrays using PHP
问题描述
我已经合并2多维数组用相同的信息,但使用 array_merge()
不同的键,我得到的输出:
I have merged 2 multidimensional arrays with the same info but with different keys using array_merge()
and I get the output:
Array
(
[0] => Array
(
[Ttitle] => lilly
[Price] => 1.75
[Number] => 3
)
[1] => Array
(
[Title] => rose
[Price] => 1.25
[Number] => 15
)
[2] => Array
(
[Title] => daisy
[Price] => 0.75
[Number] => 25
)
[3] => Array
(
[Title] => nettle
[Price] => 2.75
[Number] => 33
)
[4] => Array
(
[Title] => orchid
[Price] => 1.15
[Number] => 7
)
)
正如你所看到数组中的第一个关键名为 TTITLE
,剩下的就是标题
。我现在想的是改变这一切 TTITLE
键(只是一个目前)为标题
(像所有其他)。当我使用 array_map()
的功能,我设法改变所有的键标题
,但我也全部删除<$除了 TTITLE
键C $ C>标题值我刚换到标题
。
As you can see the first key name in the array is Ttitle
and the rest is Title
. What I want now is to change all Ttitle
keys (just the one at the moment) to Title
(like all the others). When I the use array_map()
function I manage to change all the keys to Title
but I also delete all Title
values except for the Ttitle
key I just changed to Title
.
code是如下:
if(! empty($notmatchingarray))
{
$completearray = array_merge($notmatchingarray, $datastuff2);
$completearray = array_map(function($complete) {
return array(
'Title' => $complete['Ttitle'],
'Price' => $complete['Price'],
'Number' => $complete['Number'],
);
}, $completearray);
echo "Array which includes each unique enrty from both arrays";
echo "<pre>";
print_r($completearray);
echo "</pre>";
echo "<br/>";
}
这code的输出:
Array
(
[0] => Array
(
[Title] => lilly
[Price] => 1.75
[Number] => 3
)
[1] => Array
(
[Title] =>
[Price] => 1.25
[Number] => 15
)
[2] => Array
(
[Title] =>
[Price] => 0.75
[Number] => 25
)
[3] => Array
(
[Title] =>
[Price] => 2.75
[Number] => 33
)
[4] => Array
(
[Title] =>
[Price] => 1.15
[Number] => 7
)
)
我在做错误的事情在使用本 array_map()
功能?我应该做比其他别的东西?
Am I doing the wrong thing in using this array_map()
function? Should I be doing something else other than that?
推荐答案
更好的办法,但我领导了。与您现有的code你需要设置 TTITLE
或标题
取其present:
Better ways but I'm headed out. With your existing code you need to set Ttitle
or Title
whichever is present:
$completearray = array_map(function($complete) {
$title = isset($complete['Ttitle']) ? $complete['Ttitle'] : $complete['Title'];
return array(
'Title' => $title,
'Price' => $complete['Price'],
'Number' => $complete['Number'],
);
}, $completearray);
三元运营商是一个简单的快捷键如果
/ 其他
,所以:
Ternary operator is a shortcut for a simple if
/ else
, so:
if(isset($complete['Ttitle'])) {
$title = $complete['Ttitle']; //if Ttitle is set use it
} else {
$title = $complete['Title']; //if not use Title
}
这篇关于使用array_map使用PHP多维数组更改键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!