我已使用array_merge()
合并了两个具有相同信息但使用不同键的多维数组,并获得输出:
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
,其余的是Title
。我现在想要的是将所有Ttitle
个密钥(仅限于当前的密钥)更改为Title
(与所有其他密钥一样)。当我使用array_map()
功能时,我设法将所有密钥更改为Title
,但我还删除了除了Title
密钥之外的所有Ttitle
值,我刚刚更改为{{1} }}
代码如下:
Title
此代码的输出:
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/>";
}
我在使用这个 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
)
)
函数时做错了吗?我应该做除此之外的其他事情吗?
答案 0 :(得分:3)
更好的方式,但我走了出去。使用现有代码,您需要设置Ttitle
或Title
中的任何一个:
$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是简单if
/ else
的快捷方式,因此:
if(isset($complete['Ttitle'])) {
$title = $complete['Ttitle']; //if Ttitle is set use it
} else {
$title = $complete['Title']; //if not use Title
}
答案 1 :(得分:2)
您可以尝试使用array_key_exists
功能:
$completearray = array_map(function($complete) {
return array(
'Title' => (array_key_exists('Title', $complete)
? $complete['Title']
: $complete['Ttitle']),
'Price' => $complete['Price'],
'Number' => $complete['Number'],
);
}, $completearray);
或者如果您愿意:
$completearray = array_map(function($complete) {
$titleKey = array_key_exists('Title', $complete) ? 'Title' : 'Ttitle';
return array(
'Title' => $complete[$titleKey],
'Price' => $complete['Price'],
'Number' => $complete['Number'],
);
}, $completearray);
如果数组$complete
包含密钥'Title'
,它将使用该密钥;否则它将使用密钥'Ttitle'
。