0

I am trying to create an array like the following, but this time dynamically

$taInputs = array(
    "fieldOne" => array($this->fieldOne, '0,166,198'),
    "fieldTwo" => array($this->fieldTwo, '0,166,198'),
    "fieldThree" => array($this->fieldThree, '0,166,198'),
    "fieldFour" => array($this->fieldFour, '0,166,198')
);

So, I create my Array Object

$this->data = array();

And then I have the following loop

foreach($this->document->documentData as $documentData)
{
    $this->data = array(
        $documentData->key => array($documentData->value, '228,47,57')
    );
}

At the moment, if I output the data array after the foreach loop, I only see the last entry, so it is overwriting it on each loop.

How can I create the array I am after without it being overwritten?

1
  • 2
    $this->data[] = .... perhaps? Commented Jan 11, 2016 at 11:45

2 Answers 2

4

You need to use PHP's [] to set the key on the array.

So, change $this->data to $this->data[ $documentData->key ]:

foreach($this->document->documentData as $documentData)
{
    $this->data[$documentData->key] = array($documentData->value, '228,47,57');
}

Without the variables you can manually set it like this:

$this->data[ 'fieldOne' ] = array('someValue', '228,47,57');
$this->data[ 'fieldTwo' ] = array('someValue', '228,47,57');
$this->data[ 'fieldThree' ] = array('someValue', '228,47,57');
$this->data[ 'fieldFour' ] = array('someValue', '228,47,57');

Then you can iterate over those values with:

foreach ($this->data as $key => $data) {
    print "$key => $data[0], $data[1]";
}

Usually you will want to define it like this because accessing an array by a key number is kind of annoying:

$this->data[ 'fieldOne' ] = array('documentValue' => 'someValue', 'myNumber' => '228,47,57');

So that you can easily access it with the documentValue or myNumber key:

echo $this->data['fieldOne']['documentValue'];
echo $this->data['fieldOne']['myNumber'];
Sign up to request clarification or add additional context in comments.

Comments

2

You can also do like this

foreach($this->document->documentData as $documentData)
{
    $this->data[$documentData->key] = array($documentData->value, '228,47,57');    

}

Comments

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.