-1

hi i'am using a mvc structure for my web site, i have a class that contains a multidimensional array with a class instanciation in it like this:

protected $db;

/* Construit une instance avec 4 poèmes. */
public function __construct() {
    $this->db = array(
        "01" => new Poem("Ma bohème", "rimbaud.jpg", "Arthur Rimbaud", "boheme"),
        "02" => new Poem("J'ai tant rêvé de toi", "desnos.jpg", "Robert Desnos", "reve"),
        "03" => new Poem("Chanson d'automne", "verlaine.jpg", "Paul Verlaine", "sanglots"),
        "04" => new Poem("Liberté", "eluard.jpg", "Paul Éluard", "liberte"),
    );
}

my question is how to use array_push to add values in it.(these values are from a form) and how to deal with the id of the array

  • 1. Where and how do you want to use `array_push()` ? 2. You know that you can't use `array_push()` with associative keys. – Rizier123 May 12 '15 at 12:50
  • i want to add new values to my db array (i want to use it like a database) – jacksparo4 May 12 '15 at 12:52
  • As you show us the array now you won't be able to push new values with an associative key. Also you can't use an array like a db. – Rizier123 May 12 '15 at 12:53
  • It's not multidimensional. One way: `$this->db['05'] = ...` or simply `$this->db[] = ...`. Read more in [manual](http://php.net/manual/en/language.types.array.php) – Honza Haering May 12 '15 at 12:53
  • possible duplicate of [Push item to associative array in PHP](http://stackoverflow.com/questions/3206020/push-item-to-associative-array-in-php) – Syntasu May 12 '15 at 12:55
  • ok, then how i can solve this problem and add new values to this array?? – jacksparo4 May 12 '15 at 12:57
  • see this post about this exact issue http://stackoverflow.com/questions/10094007/php-magic-method-to-catch-array-push – mic May 12 '15 at 12:58

1 Answers1

0

Try this, this might help,

  1. create an object $class = new Poem("Your values");

  2. array_push($this->db, $class);

OR array_push($this->db, new Poem("Your values"));

Mangesh Sathe
  • 1,987
  • 4
  • 21
  • 40
  • *Err.* You can't push new values with associative keys as in OP's array shown. – Rizier123 May 12 '15 at 13:02
  • string key "01" is wrong for this question you asked. Replace it with int 0. 0 => new poem(),1 => new poem()....When you use array_push , it will automatically add key to it. You don’t have to create it – Mangesh Sathe May 13 '15 at 04:05