I must be missing something obvious here... Array help

SneakyDave

Well-known member
I'm trying to do some XML stuff with a web service, and I am obviously missing something here with creating an array structure.

Basically, I want to create an array with this structure through an iterative process, maybe I'm already doing this, but I thought I'd run by more sets of eyes.

PHP:
Array ( [contacts] =>
    Array (  [name] => David [number] => 1111111111  )
    Array (  [name] => Tom [number] => 2222222222  )
)

So, an array of contacts that contains an array of names and numbers.

So I try something like this to accomplish that, although it appears to not be correct...

PHP:
$names= array();

array_push($names, array('name' => 'David', 'btn' => '1111111111'));
array_push($names, array('name' => 'Tom', 'btn' => '2222222222'));

$contacts= array('contacts' => $names);

But then the result is this:
PHP:
Array ( [contacts] =>
    Array (
        [0] => Array ( [name] => David [number] => 1111111111)
        [1] => Array ( [name] => Tom [number] => 2222222222) )
)

I understand why that happens, but is the result basically the same as what I want in the first code paragraph? In this case, the key/value pair is an integer and the array.

Maybe that's what I really want anyway, and I'm just not interpreting the structure like I should?

edited code tags to php tags
 
Last edited:
PHP:
$names[] = array('name' => 'David', 'btn' => '1111111');
$names[] = array('name' => 'Tom', 'btn' => '2222');

$contacts = array('contacts' => $names);

If you want to do your array push...
PHP:
$contacts = array('contacts' => array());

array_push($contacts['contacts'], array('name' => 'David', 'btn' => '1111111111'));
array_push($contacts['contacts'], array('name' => 'Tom', 'btn' => '2222222222'));

The reason yours wasn't working, is you were pushing to the sub array and not the main array you wanted to.
 
Last edited:
No, they do the same thing:
http://www.php.net/array_push

Realistically, you could do this with your array_push:
PHP:
$contacts = array('contacts' => array());

array_push($contacts['contacts'], array('name' => 'David', 'btn' => '111111111'), array('name' => 'Tom', 'btn' => '22222'));

It does the first code segment I provided.
 
Last edited:
I haven't seen this type of declarlation before, PHP 5.3 throws an error:
Code:
$contacts = array('contacts' => []);

syntax error, unexpected '['

But using the original examples you gave, the array structure looks like:
Code:
Array ( [contacts] => 
    Array (
     [0] => Array ( [name] => David [btn] => 1111111 )
     [1] => Array ( [name] => Tom [btn] => 2222 ) )
 )
 
Back
Top Bottom