Stevan Tosic Stevan Tosic - 4 months ago 13
PHP Question

Push data as sub Arrays in one array

I know that this is asked few times here but there is an advanced problem.

I got an array

$data
and I need to got this structure when
foreach


$data[0] => [
'value1' => string(x) "some data",
'value2' => string(x) "some other data"
];

$data[1] => ... ...


I know that can't execute
array_push
with array keys also tried code bellow but I got two big arrays. I just need one big array with small sub arrays

My Code

$authors['email'] = array();
$authors['name'] = array();
foreach (json_decode($response)->response->docs AS $docs)
{
$articleAuthors = explode(', ', $docs->authors);
$i=0;
foreach ($docs->email as $email) {
array_push($authors['email'], $email);
array_push($authors['name'], $articleAuthors[$i]);
++$i;
}
}

Answer

Try this, to get one array with little subarrays

$authors = array();
#...
foreach($docs->email as $email){
   array_push($authors, array('email'=>$email,'name'=>$articleAuthors[$i]));
   ++$i;
}
#...
Comments