Question

I have two large arrays:

$a = array('a1','a2','a3','a4'); // and so on
$b = array('b1'=>'a1', 'b2'=>'a3', 'b3'=>'a1'); // 

I would like to get the following result:

$a = array('a1'=>array('b1', 'b3'), 'a2'=>array(), 'a3'=>array('b2') );

I could just do:

foreach($a as $aa){
    foreach($b as $bb){
        // check with if then add to a
    }
}

but it would get tremendously large with bigger numbers.

So it occurred to me that if i remove each 'b' element after being added to $a the next loops will be smaller, and i would cut on resources.

However when splicing the looped array, the index does not seem to get updated, and the next loop does not take into consideration that fact that it was cut down by 1.

How can I make this work, and also, is there a better way of fitting items of an array into the appropriate indexes of another array?

EDIT:

how would this be done if the structure of both $a and $b were:

$a[0]['Word']['id']=1;
$a[0]['Word']['sentence_id']=2;
$a[0]['Word']['word_string']='someWord';

$b[0]['Word']['id']=3;
$b[0]['Word']['sentence_id']=4;
$b[0]['Word']['word_string']='someWord';

// And i would like to list `b` like so:
$a[0]['list_of_bs']=array(b[0], b[1]);
//So that i can get:
echo $a[0]['list_of_bs']['Word']['id'];
// and to get result 3

and i would like it to be $a[0][Word][list_of_b]=array(b1,b2,b3) and each of the b's has it's own data in associative array.

Was it helpful?

Solution

Try this,

$a = array('a1','a2','a3','a4');
$b = array('b1'=>'a1', 'b2'=>'a3', 'b3'=>'a1');

foreach($a as $values)
{
    $key = array_keys($b, $values);

    $new_array[$values] = $key;
}

$new_array -> will be the result that you need.

OTHER TIPS

No there is no other way which removes load from the server.

You need to do this in this way only.

Even array_walk also need to perform it like in the loopy way.

The way you put together the two loops is not well thought. Don't put them together but after each other:

foreach ($a as $aa) {
    // transform a
}
foreach ($b as $bb){
    // check with if then add to a
}

This will make count(a) + count(b) iterations instead of count(a) * count(b) iterations - which is less unless a and b have only one element.

Taking idea from @hakre ..

Why not loop through $b

new_arr = new array
foreach $b as $bb
  new_arry($bb->val).push($bb->key)

foreach $new_arry as $nn
  if $nn doesn't exist in $a then remove
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top