I'm pulling data from JSON array in php. Everything works as expected but somewhere in the loop parts gets lost, it only pulls first one. Please help. Thank you very much.
Here is Json:
$json = '
{
"theId": "fB17",
"loadId": "82387T",
"description": "Short description",
"contact": "Name of person",
"contactinfo": "Phone number or email of contact person",
"pickupaddress": "Address",
"parts": [
{ "number": "655-2032B" },
{ "number": "655-2056" },
{ "number": "655-2056" },
{ "number": "300-85091" }
]
}';
PHP code:
$data = json_decode($json);
$theId .= $data->theId;
$loadId .= $data->loadId;
$description .= $data->description;
$contact .= $data->contact;
$contactinfo .= $data->contactinfo;
$pickupaddress .= $data->pickupaddress;
ALL ABOVE GET PULLED FROM JSON AND SAVED PROPERLY
Saving data
$obj = new ElggObject();
$obj->subtype = "load";
$obj->description = strip_tags($description);
$obj->title = $title.$theId.'-'.$loadId;
$obj->contact = $contact;
$obj->contactinfo = $contactinfo;
$obj->pickupaddress = $pickupaddress;
$guid = $obj->save();
Object is saved with basic info
Now going through "parts" data from Json
foreach ($data->parts as $core_title) {
// Getting "parts' value from Json
$titlename = $core_title->number;
//Now need to use that data and find existing entity with that title in Database
$dbprefix = elgg_get_config('dbprefix');
$options['joins'][] = "JOIN {$dbprefix}objects_entity oe ON oe.guid = e.guid";
$options['wheres'][] = "oe.title = '$titlename'";
$options['types'] = array('object');
$options['subtypes'] = array('core');
$options['limit'] = 1;
$entity = elgg_get_entities($options);
// I got that entity that matches the title
//Now get GUID of the entity
foreach ($entity as $o) {
$boxg = $o->guid;
}
// It works I get the GUID as $boxg but now need to save EACH $data->parts as annotation to database
$obj->annotate('cores', $boxg);
}
IT only grabs first one fron Json ( 655-2032B )and saves only that one.
If I do this it saves each $data->parts value not just first one:
foreach ($data->parts as $core_title) {
$titlename = $core_title->number;
$obj->annotate('cores', $titlename);
}
This code makes no sense:
It goes through all items in
$entityand keeps overwriting$boxgvalue without actually doing anything with the value.The result of this foreach loop is that
$boxgholds the GUID of the last item in$entityand only then this one single value used to annotate:Is this what you really wanted to do? Shouldn't the annotate method be used inside the foreach loop?
Apart from that it's hard to give you a clear answer because your code is rather obscure and not well explained.