如何循环数组并有条件地更新嵌套值

时间:2015-12-11 03:31:49

标签: php arrays

我有两个数组:

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的值。

3 个答案:

答案 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
  • 第二个数组实际上不是一个数组,它是一个具有以下结构的SimpleXMLElement(psuedocode / JSONish语法)
 
{
  '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';
    }    
  }
}
相关问题