• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

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

SneakyDave

Well-known member
#1
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:

Jeremy

Well-known member
#2
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:

SneakyDave

Well-known member
#5
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 ) )
 )