Search code examples
phpjsonmongodbcharacter-encodingphp-mongodb

Access JSON field starting with "@" - PHP MongoDB library


I have a MongoDB database with a collection composed by persons that follows this pattern

    "_id" : ObjectId("5a3be781575621b1e1c7512d"),
    "@id" : "http://minerva.atcult.it/rdf/12749587-539f-359f-a48a-e3a2279c8fa8",
    "@type" : "foaf:Person",
    "name" : "Gallenga, Romeo"

and another collection composed by items like this

{
    "_id" : ObjectId("5a3be71b575621b1e1c73f24"),
    "@id" : "http://minerva.atcult.it/rdf/000000017103",
    "@type" : [
            "bibo:MultiVolumeBook",
            "bibo:Book"
    ],
    "creator" : [
            "http://minerva.atcult.it/rdf/9959464b-24e6-338f-b79a-5705848861cd",
            "http://minerva.atcult.it/rdf/22ef493f-52ed-3b13-9756-03db125128e1",
            "http://minerva.atcult.it/rdf/adc7ca8d-ebb5-3879-bb76-38f7344a978d",
            "http://minerva.atcult.it/rdf/3a483833-4ada-30a6-8157-f4c61c6daf47"
    ],
    "identifier" : "000000017103",
    "title" : "Replica della formella del 14 sec. del campanile di Giotto raffigurante uno studio medico",        
}

I'm working with PHP 5.6 using MongoDB library.

Goal

I want to query for items that have a particular creator (that obviously is a person).
Through the query (that works)

$authorlist=$pcollection->find(['name'=>$pregex],['projection'=>['_id'=>0,'@id'=>1,'name'=>1]]);

involving the regular expression $pregex , I retrieved a projection (cointaning the @id and name fields) of the person, then I tried to write the following query to obtain matches beetween the field creator of the items and @id field of the persons

  $documentlist=$icollection->find(['creator'=>($person->@id)]);

but it didn't work because PHP don't accept field starting with @ (IDE says "expected field name").
I also tried

$documentlist=$icollection->find(['creator'=>($person->'@id')]);

but it didn't work.
So, what's a way to access a JSON field that starts with "@" in PHP?


Solution

  • I suppose it's already a duplicate, but accessing fields with non-regular names usually done as:

    $person->{'strange-field-name'};
    // for your case it is:
    $person->{'@id'}