1

I'm trying to build an archive-class for my firebird database. And I have the following problem a couple of times already:

I want to construct an array-structure like that:

/**
 *  @var [] stores the success log of all db operations
 *
 *  $_log = Array(
 *      (string) [DATA_SOURCE] => Array(
 *          (int) [0] => Array(
 *              (string) [id]       => (int) 32,
 *              (string) [action]   => (string) "update/insert/delete",
 *              (string) [state]    => (int) 1,
 *              (string) [message]  => (string) "success/error",
 *          )
 *      )
 *  )
 */
private $_log = array();

MY 1. TRY:

// push result to log array
array_push(
    $this->_log,
    array(
        "archive"   => array(
            "id"        => $row["ID"],
            "action"    => "update",
            "state"     => $success,
        ),
    )
);

RESULTS IN:

Array(
    [0] => Array(
        [archive] => Array(
            [id] => 32
            [action] => update
            [state] => 1
        )

    )
)

That's not exactly what i want. I want the "data-source"-key here "archive" in front of the pushed entry [0].

MY 2nd TRY

array_push(
    $this->_log["archive"],
    array(
        "id"        => $row["ID"],
        "action"    => "update",
        "state"     => $success,
    )
);

RESULTS IN

<br />
<b>Warning</b>:  array_push() expects parameter 1 to be array, null given in <b>/Users/rsteinmann/web/intranet/pages/firebird/ArchiveTables.php</b> on line <b>238</b><br />

I'm a bit helpless with this task. I also tried to find anything on google or stackoverflow but there was nothing really useful.

I would be so glad if someone could help me with that!

Thank you, Raphael

1 Answer 1

2
$this->log['archive'][] = array('id' => ...);

This is the sanest way to do it. PHP will create any non-existing keys (like archive) for you. array_push on the other hand is a function call and requires its arguments to already exist, it can't create a non-existing archive key for you. You'd have to do that before you call the function.

array_push is mostly useful if you need to push several arguments at once (array_push($arr, $a, $b, $c)), otherwise $arr[] = $a is the generally preferred and officially recommended syntax.

Sign up to request clarification or add additional context in comments.

1 Comment

Now I feel sort of stupid :-D But yea this was the exact solution! Thank you so much, also for the explanation! For some reason i did not know that one can use empty key-brackets [].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.