Jump to content

Merging arrays like this - help!


phplemon

Recommended Posts

You could do

$array = array(5 => 'first', 3 => 'first', 2 => 'secound', 4 => 'secound');

$array_values = array_unique(array_values($array));

printf('<pre>%s</pre>', print_r($array_values, true));

foreach($array_values as $value)
{
    echo $value .' = ' . array_sum(array_keys($array, $value)) . '<br />';
}

You can't.

 

Array key values must be unique and you cannot guarantee that when you start adding them. You need to to rethink your array structure

Ok, can I make it so that it adds 5 + 3 + an extra 100 to make sure its unique? So the array becomes like this:

Array ( [108] => first [106] => second )

 

You could do

$array = array(5 => 'first', 3 => 'first', 2 => 'secound', 4 => 'secound');

$array_values = array_unique(array_values($array));

printf('<pre>%s</pre>', print_r($array_values, true));

foreach($array_values as $value)
{
    echo $value .' = ' . array_sum(array_keys($array, $value)) . '<br />';
}

Thank you, in the end it gives me this:

Array
(
    [0] => first
    [2] => secound
)
first = 8
secound = 6

Im going to merge the array with another array so this doesnt really work for me.

Maybe I can use this as an array inside another array and still get the result I want.

 

Thx.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.