php多维数组,搜索和更新如果存在或插入,如果不存在
问题描述:
我已经搜索,没有发现任何东西。php多维数组,搜索和更新如果存在或插入,如果不存在
我想就如何搜索多维数组和更新如果存在值或如果它不存在插入一些建议或指针。
例如,在现阶段,我创建这些值这样的数组:
Array
(
[0] => Array
(
[quantity] => 1
[supplier_paypal] => [email protected]
[supplier_price] => 10
)
[1] => Array
(
[quantity] => 2
[supplier_paypal] => [email protected]
[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 = '[email protected]';
$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()
文档中从one of the comments摘自:
<?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 */
}