0

I've got two arrays, an array of integers and an array of strings. I want to combine these two, but this is proving troublesome to me.

Basically, the first value in each array will be associated, the second value of each array will be associated, third with each other, and so on.

I've got a foreach loop iterating over and using $result as array key, as such:

foreach ($results as $result) {

And then a function to generate $order based on said string.

I am then trying to associate each value as I said, where I would have something like:

array('8' => 'value', '8' => 'value', '6' => 'anothervalue', '6' => 'anothervalue');

Here's the code I have.

$order = resource_library_apachesolr_resource_type_order($resource_type);
$result['resource_type'] = $resource_type;
$newresults = array($order => $result);

$order isn't iterating, so how would I make it so that I get the iterated value of $order combined with the currently iterating value of $result?

Vivek Jain
  • 3,811
  • 6
  • 30
  • 47
Steven Matthews
  • 9,705
  • 45
  • 126
  • 232
  • 1
    `'8' => 'value', '8' => 'value'...` same key in array? this will not work. – Narek Feb 05 '14 at 13:41
  • As @Narek mentions same keys won't work, but if you want to output it, you can use http://stackoverflow.com/questions/2516599/php-2d-array-output-all-combinations – Michal Brašna Feb 05 '14 at 13:42

2 Answers2

0

Well, since you have repeated keys, you can't use array_combine

You might have to get a bit creative. Maybe casting to string and adding 0 before the integer part...

EXAMPLE:

$a1 = array(1,1,2,3,3);
$a2 = array('a', 'b', 'c', 'd', 'e');
$a3 = array();

for ($i=0; $i<count($a1); ++$i) {
    $key = (string) $a1[$i];
    $val = (String) $a2[$i];
    while (isset($a3[$key])) {
        $key = "0$key";
    }
    $a3[$key] = $val;
}

var_dump($a3);

foreach ($a3 as $key => $val) {
    $key = (int) $key;
    print "$key=>$val<br>";
}

OUTPUTS:

array (size=5)
  1 => string 'a' (length=1)
  '01' => string 'b' (length=1)
  2 => string 'c' (length=1)
  3 => string 'd' (length=1)
  '03' => string 'e' (length=1)
1=>a
1=>b
2=>c
3=>d
3=>e
Tivie
  • 18,864
  • 5
  • 58
  • 77
0

I don't know why you need this, but if I want to do something like that I'll do:

$arr = array();
foreach($numbers as $i=>$num){
    $arr[$num][] = $strings[$i];
}

and will get:

array(
    1 => array(
        a,
        b
    ),
    2 => array(
        c
    ),
    3 => array(
        d,
        e
    )
)
Narek
  • 3,813
  • 4
  • 42
  • 58