Page 1 of 1

How to update multidimensional arrays

Posted: Thu Jul 28, 2005 8:13 pm
by unidude
Hello guys,

Just a quick quesiton

I want to only update some arrays within the existing array,

$oldArray = array('ArrTitle1' =>array('arrayValue1','arryValue2') 'ArrTitle2'=>array('arrayValue1','arrayValue2) .....'ArrTitle5'=>array('arrayValue1','arrayValue2')......'ArrTitle18'=>array('arrayValue1','arrayValue2'))
//sizeOf($oldArray) is 19

$curArray =array('ArrTitle5'=>array('NEWarrayValue1','NEWarrayValue2') 'ArrTitle6'=>array('NEWarrayValue1','NEWarrayValue2') .......'arrTitle15'=>array('NEWarrayValue1','NEWarrayValue2')
//sizeOf($curArray) is 15


I was thinking of using combination of foreach() and if statement to find the key and replace with the value , such as following

foreach($oldArray as $key=>$val){
if ($key == 'arrTitle5' || $key == 'arrTitle6' ){ //line 2
foreach ($val as $valueKey=>$value){
$oldArray[$valueKey] = $value;
}
}

}

As you can see from the above code, on line 2
Its not very smart as if I want to update 10 arrays then it will be a long list and I see it as a quick fix, which cannot be reused in the future.


Just wondering if anyone know how to make it more dynamic and less static.

Greatly appreciate it

Posted: Thu Jul 28, 2005 8:23 pm
by harrisonad
first of all, use php tags for displaying your code.
Diving deep to the deepest array values can be a tiring job but easy to do.

Code: Select all

// searching and retrieving
foreach($aray as $parent){
  foreach($parent as $child){
    foreach($child as $grandchild){
      // etc...
    }
  }
}
// retrieving
$value = $aray['parent']['child']['grandchild'];
// updating
$aray['parent']['child']['grandchild'] = $value;

Posted: Thu Jul 28, 2005 10:36 pm
by unidude
Thans harrisonad
For your fast reply.
I used your code doesnt seem to work for my purpose but you have gave me ideas to improve my code,this is the following

Code: Select all

foreach ($curArray as $parentKey=>$parentVal){
		foreach ($parentVal as $childKey=>$childVal){
			$oldArray[$parentKey][$childKey] = $curArray[$parentKey][$childKey];	
		}
	}
This will replace the existing one and wont erase the one that has not been found.

Regards,

Posted: Fri Jul 29, 2005 1:30 am
by harrisonad

Code: Select all

foreach ($curArray as $parentKey=>$parentVal){
    foreach ($parentVal as $childKey=>$childVal){
        $oldArray[$parentKey][$childKey] = $childVal; // <--  simpler
    }
}
But i suggest you read about array functions from the manual. Some functions allows you to search and replace array values.

Posted: Sat Jul 30, 2005 7:24 am
by unidude
Thanks very much harrisonad

you've been a great help :wink: