meredevelopment
9 months ago

Help needed adding key-value pair to sub-array in collection.

Posted 9 months ago by meredevelopment

Hi, I've had all sorts of trouble trying to add a key=>value pair to an array nested in a collection. I thought it would be easy with a collection method but... nope, been messing about with this for longer than my dignity allows me to say. All the things I've attempted with merge(), push() etc want to work on a collection not array. So I've ended up going back to basics and it's ugly!

Here's an example. It's completely fictitious but perfect illustrates the problem. In the example I have achieved what I want, but it's a joke! there must be a faster easier more succinct way:

$collection = collect([
    [
        'bid' => 2,
        'type' => 'Onion'
    ],
    [
        'bid' => 12,
        'type' => 'Clove'
    ],
    [
        'bid' => 19,
        'type' => 'Apple'
    ],
    [
        'bid' => 39,
        'type' => 'Clove'
    ]
]);
dump($collection);

// Find the key of the first 'Clove' entry
$foundCollectionKey = $collection->search(function ($item, $key) {
    return $item['type'] === 'Clove';
});

dump($foundCollectionKey);

// Extract the array data of the first 'Clove' entry.
$firstWhereArray = $collection->firstWhere('type', 'Clove');
dump($firstWhereArray);

// Append a key value pair.
$firstWhereArray['category'] = 'spice';

dump($firstWhereArray);

// Put the modified collection item back where it came from by Key.
$collection->put($foundCollectionKey, $firstWhereArray);

dump($collection);

This is the collection I want to end up with:

Collection {#419 ▼
  #items: array:4 [▼
    0 => array:2 [▼
      "bid" => 2
      "type" => "Onion"
    ]
    1 => array:3 [▼
      "bid" => 12
      "type" => "Clove"
      "category" => "spice"
    ]
    2 => array:2 [▼
      "bid" => 19
      "type" => "Apple"
    ]
    3 => array:2 [▼
      "bid" => 39
      "type" => "Clove"
    ]
  ]
}

I should say that this data is eventually going to be stored as JSON (TEXT) in a DB cell in this format:

{
    "foods": [{
            "bid": 2,
            "type": "Onion"
        },
        {
            "bid": 12,
            "type": "Clove",
            "category": "Spice"
        },
        {
            "bid": 19,
            "type": "Apple"
        },
        {
            "bid": 39,
            "type": "Clove"
        }
    ]
}

Please sign in or create an account to participate in this conversation.