-2

If I wanted to create an array in PHP with the following format, what would be the best way to approach it? Basically I want to declare the array beforehand, and then be able to add the values to person_id, name and age.

'person_id' => array('name'=>'jonah', 'age'=> 35)

3 Answers 3

1

To the first answer @Joe, first of all, your class doesn't support encapsulation since your attributes are public. Also, for someone who doesn't know how to create an array, this concept may be a bit complicated.

For the answer, changing a bit the class provided by @Joe, PHP provide a simple way of using arrays:

If you need many rows for this array, each row has a number, if not, remove the [0] for only one entry.

$persons = array();

$persons[0]['person_id'] = 1;
$persons[0]['name'] = 'John';
$persons[0]['age'] = '27';
Sign up to request clarification or add additional context in comments.

7 Comments

Actually there is one small thing I do want to ask, if I were to use the code in a for loop (for multiple records), would I simply remove the 0 from $persons[0]?
exactly and replace it with a variable that is incremented such as while($i < $numberOfLoops) {$persons[$i]['person_id'] = 1;}
Simpley omitting the 0 (and only the 0) will have PHP automatically create an index for each record. This is useful if you are using your array merely as a collection and do not rely on the indices: while(...) { $person = array(); $person['name'] = 'xyz'; $person['age'] = ...; $persons[] = $person; } will add each $person you create in the loop to the $persons array, assigning indices starting from 0 to them.
Yes, but if you remove the 0, you will lose track of the previous information stored in the array.
Right, you have to fill in the subarray locally and add it to $persons as the last step (like I did in the example). EDIT: array_push is the same as $persons[], and it's recommended to use the latter one, see php.net/array-push
|
1

Depending on how you want to use it, you could make a simple object:

class Person
{
    public $person_id;
    public $name;
    public $age;
}

$person = new Person; // make the object beforehand
$person->person_id = 123; // their id
$person->name = 'Joe'; // my name
$person->age = 21; // yeah, right

This is virtually identical to an array (in terms of how it's used) except for:

  • Instead of new array() you use new Person (no brackets)
  • Instead of accessing items with ['item'] you use ->item

2 Comments

Seems a bit overkill for array data.
Aye, but it's an option :) Not the best, but an option.
1

You can start with an empty array:

$arr = Array();

Then add stuff to that array:

$arr['person_id'] = Array();
$arr['person_id']['name'] = "jonah";
$arr['person_id']['age'] = 35;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.