2

I have and associated array looking like this:

array(225) {
  [0]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["firstname"]=>
    string(2) "me"
    ["lastname"]=>
    string(2) "ab"
  [1]=>
  array(3) {
    ["id"]=>
    string(1) "2"
    ["firstname"]=>
    string(3) "you"
    ["lastname"]=>
    string(2) "bc"

As you may the structure of all elements is identical. What I want to do is to create dynamiclly new key in the nested arrays, something like this :

array(225) {
      [0]=>
      array(4) {
        ["id"]=>
        string(1) "1"
        ["firstname"]=>
        string(2) "me"
        ["lastname"]=>
        string(2) "ab"
        ["newKey"]=>
        string() "1,2,3,....n" 
      [1]=>
      array(3) {
        ["id"]=>
        string(1) "2"
        ["firstname"]=>
        string(3) "you"
        ["lastname"]=>
        string(2) "bc"
        ["newKey"]=>
        string() "1,2,3,....x" 

and I want to add new records to the value with key ["newKey"] but in a way that the old value is not deleted but as shown above - we separate every new value with comma from the others.

I tried array_push and some other things but can't get the exact result I want.

1 Answer 1

3

I don't know if it's quite what you want, but seems like something like this might do the trick:

function addField(array &$aData, $newVal)
{
    foreach($aData as $aUnit)
        if(array_key_exists('newKey', $aUnit))
            $aUnit['newKey'] .= ",$newVal";
        else
            $aUnit['newKey'] = '1';
}

Let me know if you'd like that expanded upon if it isn't enough of a base to get you rolling.

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

2 Comments

That's exactly what I needed, althoug I don't quite understand the need from reference but it's more like a theoretical question.
The reference will prevent a copy of the array from being made. The alternative would be to not have a pass-by-reference, in which case calls to the function would look like $aData = addField($aData, 5);. You see there, you're creating a new array and replacing the old one instead of just modifying the existing array.

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.