Here is some example of my code
$data = array('code'=>'100','txt'=>'success');
$movie = array('name'=>'movie', array(array('id'=>'1','name'=>'movie1'),array('id'=>'2','name'=>'movie2')));
$anime = array('name'=>'anime', array(array('id'=>'1','name'=>'anime1'),array('id'=>'2','name'=>'anime2')));;
How can I put $movie and $anime into $data['data'] ? I try array_push and $data['data'] = array($movie,$anime);
or $data['data'][] = array($movie,$anime);
and it didnt work.
oh sorry I just want it to xml ( I have function that convert array to xml )
now I use $data['data']['item'][] = array($movie,$anime);
so here's my xml
<xml>
<data>
<item>[movie]</item>
<item>[anime]</item>
</data>
<xml>
my question is , Is there another way to put it to data without ?
There are multiple ways to accomplish this:
$data['data'] = array($movie, $anime]);
Using the short array syntax, it's even easier:
$data['data'] = [$movie, $anime];
If you're doing this inside a loop, then add them one at a time:
$data['data'] = array();
$data['data'][] = $movie;
$data['data'][] = $anime;
Or if you want to use array_push()
:
$data['data'] = array();
array_push($data['data'], $movie);
array_push($data['data'], $anime);
That depends, do you want both anime and movie arrays in one key of the main array, or in separate ones example:
$data['anime'] = $anime;
$data['move'] = $movie;
Would be accessed like $data['anime']['name']; etc, or you could put them both under data, like your question implies like so
$data['data'] = array($anime, $movie);
Which could be accessed like $data['data'][1]['name'] for the movie array, and 0 for the anime array.
First, you need to understand how array_push
works. It will insert an element to the end of the array and it will give it a numeric key based on the highest numeric key available. If there are no numeric keys (eg all text), then the numeric key will be zero.
For example:
php > $a = array('b','c');
php > array_push($a, 'd');
php > print_r($a);
Array
(
[0] => b
[1] => c
[2] => d
)
All keys in the above example are letters because we haven't create an associative array. But if we do create an associative array, it will look like:
php > $b = array('a'=>'a');
php > array_push($b, 'c');
php > print_r($b);
Array
(
[a] => a
[0] => c
)
If you use array_push
or array_shift
on the $data
array, you will add the data you want to add but without an associative array index, something that you can refer to, in this case 'data'.
To add, you can do:
$data['data'] = array($movie, $anime);