Chris Hamant
Chris Hamant

Reputation: 35

Easier way to get back values from DynamoDB using SDK2 for PHP?

All of the methods and iterators that return results from DynamoDB seem to contain the following format (in json style):

{key : [TYPE,value]}

Where 'TYPE' is N,S...

I want them to be in the format:

{key : value}

Where 'value' is a String if S and a number if N (or an array of such if in set form).

The API contains a helper method to format attributes by type from an array: http://docs.aws.amazon.com/aws-sdk-php-2/latest/class-Aws.DynamoDb.DynamoDbClient.html#_formatAttributes

Is there a pre-existing helper method or flag that will do the inverse for results that I've overlooked?

I know implementation of this is somewhat trivial - It just seems to be a bit of work to do the conversion every time I was to use a result. (here is a naive version providing just the 'N' and 'S' cases)

$iterator = $client->getIterator('Scan',$params);
foreach($iterator as $item){
    $newitem = [];
    foreach($item as $k => $v){
        foreach($v as $type => $actualv){
            switch($type){
                case 'S' :
                    $newitem[$k] = $actualv;
                    break;
                case 'N' :
                    $newitem[$k] = (int)$actualv;
                    break;
            }
        }
    }
    echo json_encode($newitem).PHP_EOL;
}

Is there a method I overlooked to make this easier without having to loop over every key?

Upvotes: 2

Views: 1113

Answers (1)

Jeremy Lindblom
Jeremy Lindblom

Reputation: 6527

[EDIT: Before version 2.4.1 of the SDK,] there isn't a really a pre-existing helper for this, but since your are using getIterator, you can use some iterators magic. Try something like this (building off your original code):

$iterator = $client->getIterator('Scan', $params);
$iterator = new \Guzzle\Iterator\MapIterator($iterator, function ($item) {
    return array_map('current', $item);
});

foreach ($iterator as $item) {
    // Get a single attribute value
    echo $item['attribute_name'] . "\n";

    // Print the item attributes
    echo print_r($item);
}

EDIT: For version 2.4.1+, you can use the included ItemIterator class that does something similar to what I did with the MapIterator.

$iterator = $client->getIterator('Scan', $params);
$iterator = new \Aws\DynamoDb\Iterator\ItemIterator($iterator);

foreach ($iterator as $item) {
    // Get a single attribute value
    echo $item['attribute_name'] . "\n";

    // Print the item attributes
    echo print_r($item->toArray());
}

EDIT: See also Iterating through Amazon DynamoDB Results

Upvotes: 2

Related Questions