我有两个数组:
array (size=4)
0 => string '5' (length=1)
1 => string '4' (length=1)
2 => string '2' (length=1)
3 => string '2' (length=1)
3 => string '8' (length=1)
还有一个我从XML文件加载的数组:
object(SimpleXMLElement)[1]
public 'book' =>
array (size=101)
0 =>
object(SimpleXMLElement)[2]
public 'id' => string '1' (length=1)
public 'title' => string 'p' (length=1)
1 =>
object(SimpleXMLElement)[3]
public 'id' => string '2' (length=1)
public 'title' => string 'pp' (length=2)
2 =>
object(SimpleXMLElement)[4]
public 'id' => string '3' (length=1)
public 'title' => string 'pen' (length=3)
3 =>
object(SimpleXMLElement)[5]
public 'id' => string '4' (length=1)
public 'title' => string 'lapton' (length=6)
......
......
101 =>
object(SimpleXMLElement)[103]
public 'id' => string '101' (length=1)
public 'title' => string 'title' (length=5)
我想将第二个数组的键id
的每个值与每个值的第一个数组的键进行比较。当它相同时,我想更新第二个数组的键title
的值。
答案 0 :(得分:1)
假设您的第一个数组是$idArray
而第二个数组是$xmlArray
,您可以使用类似的内容。
$result = array_map(function($xmlElement) use ($idArray) {
if (in_array($xmlElement->id, $idArray)) {
$xmlElement->title = 'updated value';
}
return $xmlElement;
}, $xmlArray);
答案 1 :(得分:0)
$array1
$fromXML
{
'book' => {
0 => SimpleXMLElement {
'id' => 1,
'title' => 'p'
}
}
}
$fromXML['book']
$fromXML['book'][0]['id']
$fromXML['book'][0]['title'][0] = 'new title'
基于How can I set text value of SimpleXmlElement without using its parent?和PHP SimpleXML, how to set attributes?以及PHP foreach change original array values
foreach($fromXML['book'] as $key => $element) {
if(array_key_exists($element['id'], $array1)) {
$fromXML['book'][$key]['title'][0] = $array1[$element->id];
}
}
我没有测试过这个,只是关闭了文档。如果我误解了SimpleXMLElement数组的结构,请尝试使用var_dump($fromXML['some']['key'])
进行试验,直到找到正确的方式来访问数组/元素
注意:显然,array_key_exists()
performs better than in_array()
on large arrays
答案 2 :(得分:-1)
立即尝试
foreach($array1 as $arr1 => $val1){
foreach($array2 as $arr2 =>$val2){
if($arr1==$arr2){
$val2['title']='update value';
}
}
}