1

I have arrays as follows:

$A = ["a","b","c"];
$B = ["1" , "2", "3"];

I am trying to create an array as follows:

Array(["test"] => "a"
      "val"=>1),
    (["test"] => "b"
      "val"=>2),
   (["test"] => "c"
      "val"=>3)

I did something like this:

$data =array();


for($i=0;$i<count($A);$i++){

$data["test"]  = $A[$i] ;
$data['val']  = $B[$i] ;

}

But I am getting only the last value in resultant array as:

Array(["test"] => "c"
          "val"=>3)

The first two elements missing. please help me.

4 Answers 4

2

You can use array_map function as

$result = array_map(function($a,$b){return ['test' => $a,'val' => $b];},$A,$B);
print_r($result);
Sign up to request clarification or add additional context in comments.

Comments

2

you code is rewrite values of array every time loop execute.so you have to create multidimensional array.this will show you data as you want..

 $data =array();


    for($i=0;$i<count($A);$i++){

    $data[]  = array('test' =>$A[$i],'val'=>$B[$i]) ;


    }

1 Comment

thanks @KevinBrown next time i will be careful with that
1

You just overwriten the value of $data['test'] and $data['val']. It should be a 2 dimentional array and The following code should solve your issue mate..

$A = ["a", "b", "c"];
$B = ["1", "2", "3"];

$data = array();
for ($i = 0; $i < count($A); $i++) {

    $data[$i]['test'] = $A[$i];
    $data[$i]['val'] = $B[$i];
}

1 Comment

I have explained the answer.
0

$data["test"] and $data["test"] are being overwritten. You need to make them array.

Try

$A = ["a","b","c"];
$B = ["1","2","3"];

for($i=0;$i<count($A);$i++)
{
    $data[$i]["test"] = $A[$i];
    $data[$i]['val'] = $B[$i];
}

print_r($data);

1 Comment

its just identical to mine !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.