Jump to content

Another Intense PHP Problem... Help

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
6 replies to this topic

#1
DEViANT

DEViANT

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 358 posts
Right! Scenario. I've got two arrays. Both are populated through a database, but its processed a bit beforehand. What it comes down to is this :

$array1[$i][$key] = $x;


$array2[$string][$key] = 0;



Now what I want to do is copy $x from array 1 to array 2 IF array 1 key name is equal to array 2 key name. thus if the $key from array 1 == $key from array 2

.......


Anyone? Please? I've read up a buttload of stuff on array functions on php.net but can't really find something that works for me. I've been struggling now for the good part of a day to write my one, But I get the feeling Im going more off-track with every line I code..

#2
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
untested
$keys = array_keys($array1[$i]);

foreach($keys as $key)

    if(array_key_exists($key, $array2)) 

        $array2[$i][$key] = $array1[$i][$key];



#3
bythos

bythos

    Newbie

  • Members
  • PipPip
  • 14 posts
Not the most efficient solution could be improved on.

Hope it works.


header("Content-type: text/plain");



$array1 = array(array('a'=>5, 'c'=>7),array('d'=>50,'b'=>9));

$array2 = array('e'=>array('a'=>6, 'c'=>9),'uo'=>array('b'=>10));

echo "before\n";

print_r($array1);

print_r($array2);


foreach($array1 as &$i){

	foreach($i as $key => $x){

		foreach($array2 as &$string){

			foreach($string as $key2 => $value){

				if($key == $key2){

					$string[$key2] = $x;

				}

			}

		}

	}

}

echo "after\n";

print_r($array1);

print_r($array2);



#4
DEViANT

DEViANT

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 358 posts
Thanks allot for the replies. I ended up using the suggestion posted by bythos. It works! And so, I can continue coding the script. Thanks guys :)

#5
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
n^4 algorithms make my cry.

#6
bythos

bythos

    Newbie

  • Members
  • PipPip
  • 14 posts
Its bad i know make me cry too. Its a brute.

I'll try make it better soon.

#7
PsychoCoder

PsychoCoder

    Learning Programmer

  • Members
  • PipPipPip
  • 92 posts
Couldnt you write a simple function like this to accomplish this?

function array_intersect_key($array1, $array2) 

{

  $res = $array2;

  foreach($array1 as $key=>$value) 

 {

             if(array_key_exists($key, $array2)) 

			$res[$key] = $array1[$key];

  }

  return $res;

}

SELECT * FROM Users WHERE Clue > 0;
ERROR: 0 results returned
Posted Image