我已经搜索过了,但没有找到任何相关信息。
我想要一些关于如何搜索多维数组并在值存在时更新或在值不存在时插入的建议或指针。
例如。目前,我创建了一个数组,其中包含以下值:
Array
(
[0] => Array
(
[quantity] => 1
[supplier_paypal] => paypalaccount1@paypal.com
[supplier_price] => 10
)
[1] => Array
(
[quantity] => 2
[supplier_paypal] => paypalaccount2@paypal.com
[supplier_price] => 20
)
)
现在这很好,但它只是循环,并且可以在数组中创建重复的电子邮件地址。我需要一些我可以放在循环中搜索的东西,看看电子邮件是否存在,如果存在,那么只需将供应商价格加在一起。
有什么帮助或想法吗?
以下是我尝试过的:
$arrIt = new RecursiveIteratorIterator(
new RecursiveArrayIterator($this->data['payrecipient_data']));
foreach ($arrIt as $sub) {
$subArray = $arrIt->getSubIterator();
if ($subArray['supplier_paypal'] === $supplier_info['supplier_paypal']) {
$this->data['payrecipient_dup'][] = iterator_to_array($subArray);
} else {
$this->data['payrecipient_nondup'][] = iterator_to_array($subArray);
}
}
这使我能够搜索并将数组分为重复数组和非重复数组。
但我不知道从哪里开始更新数组,所以我迷路了,陷入了困境。
$needle = 'foo@bar.com';
$found = false;
foreach ($array as &$element) {
if ($element['supplier_paypal'] == $needle) {
// update some data
$element['foo'] = 'bar';
$found = true;
break;
}
}
unset($element);
if (!$found) {
$array[] = array('supplier_paypal' => $needle, ...);
}
有更优雅的方法可以对数据进行索引,从而更快地找到数据,而无需每次都循环整个过程,但这本质上是您要寻找的基本算法。
摘自PHP的str_replace()
文档中的一条注释:
<?php
function str_replace_json($search, $replace, $subject){
return json_decode(str_replace($search, $replace, json_encode($subject)));
}
?>
假设您的数组名称为arr1。使用以下
$email = /*Your email to check*/;
$flag = 0; // td check if email has found or not
foreach($arr1 as $temp)
{
if($temp->supplier_paypal == $email) //email matches
{
/*add supplier price....*/
$flag=1;
}
}
if($flag == 0)
{
/*Your logic */
}