I am trying to reconstruct an object from code. First I explode the calls to the object into an array, and then convert the array into an object, and then test to see if the call works.
The object created seems fine, but the test call fails.
$claim = new_client();
print_r($claim);
$pat = $claim->patientFirstName();
echo $pat;
function new_client()
{
$text = '
$claim->patientFirstName()
UNWANTED STUFF.
$claim->patientMiddleName()
UNWANTED STUFF.....
$claim->patientLastName() ';
$client = array();
$i = 1 ;
$array = (explode("claim->",$text));
foreach ($array as &$variable) {
$variable = substr($variable, 0, strpos($variable, "()"));
$client[$variable] = $i;
$i++;
}
unset ($variable);
$object = new stdClass();
foreach ($client as $key => $value)
{
$object->$key = $value;
}
return $object;
}
Here is the result.
stdClass Object ( [] => 1 [patientFirstName] => 2 [patientMiddleName] => 3
[patientLastName] => 4 )
Fatal error: Uncaught Error: Call to undefined method
stdClass::patientFirstName()...
So any ideas as to why
$pat = $claim->patientFirstName();
is failing?
You are accessing the element is a wrong way.
$claim->patientFirstName
$claim->patientMiddleName
Related
I am trying to build an object that will hold multiple objects based of iterating through an array:
<?php
$final_object = new stdClass();
$array = ['one','two'];
$temp_str = '';
foreach ($array as $value) {
$temp_str .= $value . '->';
}
$temp_str = rtrim($temp_str, '->');
$final_object->$temp_str = 999;
print_r($final_object);
exit;
As you can guess, the parser treats '->' as a string literal and not a PHP object operator.
Is what I am attempting to do possible?
Eventually, I want to build a json string after json_encoding to: {"one":{"two": 999}}
You could store a reference of the object during the loop and assign your value at the end:
$final_object = new stdClass();
$array = ['one','two'];
$ref = $final_object ;
foreach ($array as $value) {
$ref->$value = new stdClass() ;
$ref = &$ref->$value ; // keep reference of last object
}
$ref = 999; // change last reference to your value
print_r($final_object);
Outputs:
stdClass Object
(
[one] => stdClass Object
(
[two] => 999
)
)
You could do the same using arrays:
$array = ['one','two'];
$final_object = [];
$ref =& $final_object;
foreach ($array as $value) {
$ref[$value] = [];
$ref =& $ref[$value];
}
$ref=999;
echo json_encode($final_object);
Outputs:
{"one":{"two":999}}
Is it possible to set property values of an object using a foreach loop?
I mean something equivalent to:
foreach($array as $key=>$value) {
$array[$key] = get_new_value();
}
EDIT: My example code did nothing, as #YonatanNir and #gandra404 pointed out, so I changed it a little bit so it reflects what I meant
You can loop on an array containing properties names and values to set.
For instance, an object which has properties "$var1", "$var2", and "$var3", you can set them this way :
$propertiesToSet = array("var1" => "test value 1",
"var2" => "test value 2",
"var3" => "test value 3");
$myObject = new MyClass();
foreach($propertiesToSet as $property => $value) {
// same as $myObject->var1 = "test value 1";
$myObject->$property = $value;
}
Would this example help at all?
$object = new stdClass;
$object->prop1 = 1;
$object->prop2 = 2;
foreach ($object as $prop=>$value) {
$object->$prop = $object->$prop +1;
}
print_r($object);
This should output:
stdClass Object
(
[prop1] => 2
[prop2] => 3
)
Also, you can do
$object = new stdClass;
$object->prop1 = 1;
$object->prop2 = 2;
foreach ($object as $prop=>&$value) {
$value = $value + 1;
}
print_r($object);
You can implement Iterator interface and loop through the array of objects:
foreach ($objects as $object) {
$object->your_property = get_new_value();
}
Hacked away at this for a few hours and this is what i finally used. Note the parameters passed by reference in two places. One when you enter the method and the other in the foreach loop.
private function encryptIdsFromData(&$data){
if($data == null)
return;
foreach($data as &$item){
if(isset($item["id"]))
$item["id"] = $this->encrypt($item["id"]);
if(is_array($item))
$this->encryptIdsFromData($item);
}
}
I don't work with PHP very often, at least not at this level, so I need some help. I have a SOAP response in PHP that turns into an Object:
stdClass Object
(
[Food_Document] => stdClass Object
(
[Food_Type] => Fruit
[Food_Serial] => 923490123
[Food_Name] => Apple
[Food_PictureName] => rotten_apple.jpg
[Food_PictureData] => sdlkff90sd9f90af9903r90wegf90asdtlj34kljtklsmdgkqwe4otksgk
)
)
What I need is the data from Food_PictureName and Food_PictureData, but it explodes with a warning every time I try to access it if it doesn't exist. Some objects will contain Food_PictureName and Food_PictureData, but not all of the time. Sometimes, only one or the other will exist, or neither. Basically, "0 or more times."
Here's the code I'm using:
function get_food_photo($serial)
{
$soap = new SoapClient("WSDL_LINK", array('trace' => true));
$params = new StdClass;
$params->serialNumber = $serial; // or whatever serial number you choose
$res = $soap->GetFoodDocuments($params);
$res = $res->GetFoodDocumentsResult;
$thumbnail_data = $res->FoodDocument[0]->Food_PictureData;
$ext = str_replace('.', '', $res->FoodDocument[0]->Food_PictureExtension);
return '<img src="data:image/'.$ext.';base64,'.$thumbnail_data.'"/>';
}
Now, accessing this data and displaying it DOES work if the Food_PictureData property is not null or empty, but otherwise, it will generate a warning every time: Fatal error: Cannot use object of type stdClass as array
I have tried the following: isset(), empty(), property_exists(), __isset(), strlen(), and some others.
How do I get this data without throwing an exception if it doesn't exist?
Rewrite the function as
function get_food_photo($serial)
{
$soap = new SoapClient("WSDL_LINK", array('trace' => true));
$params = new StdClass;
$params->serialNumber = $serial; // or whatever serial number you choose
$res = $soap->GetFoodDocuments($params);
$res = $res->GetFoodDocumentsResult;
if (is_array($res->FoodDocument)) {
$document = $res->FoodDocument[0];
} else {
$document = $res->FoodDocument;
}
if (property_exists($document, 'Food_PictureData')) {
$thumbnail_data = $document->Food_PictureData;
} else {
$thumbnail_data = '';
}
if (property_exists($document, 'Food_PictureExtension')) {
$ext = str_replace('.', '', $document->Food_PictureExtension);
} else {
$ext = '';
}
return '<img src="data:image/'.$ext.';base64,'.$thumbnail_data.'"/>';
}
This works:
public function import_tickets($user = null) {
$tickets = kyTicket::getAll(
kyDepartment::getAll(),
kyTicketStatus::getAll(),
array(),
kyUser::getAll()
);
$reflect = new ReflectionClass($tickets);
$ts = $reflect->getProperty('objects');
$ts->setAccessible(true);
$content = $ts->getValue($tickets);
$output = '';
foreach ( $content as $c ) {
$output .= $c->id . "\n";
}
print_r($output);
}
OUTPUT:
[root#matthewharris External]# php test.php
1
2
3
4
5
6
I am trying to access the display_id from the following object:
[4] => kyTicket Object
(
[id:protected] => 5
[flag_type:protected] => 0
[display_id:protected] => RXH-123-45678
[department_id:protected] => 5
[status_id:protected] => 3
[priority_id:protected] => 1
But when I do I get the following error:
[02-Oct-2014 12:14:29] PHP 3. kyObjectBase->__get($api_field_name = 'display_id') /var/www/html/site/public_html/inc/QA/External/test.php:43
[02-Oct-2014 12:14:29] PHP 4. trigger_error('Undefined property: kyTicket::$display_id', 1024) /var/www/html/site/public_html/inc/QA/External/api-kayako/kyObjectBase.php:573
[02-Oct-2014 12:14:29] PHP Notice: Undefined property: kyTicket::$display_id in /var/www/html/site/public_html/inc/QA/External/api-kayako/kyObjectBase.php on line 573
Why can I access id without issue but display_id will not be captured?
$reflect = new ReflectionClass($tickets);
$reflectionProperty = $reflect->getProperty('objects');
$reflectionProperty->setAccessible(true);
$objects = $reflectionProperty->getValue($tickets);
// you need object "tickets" - property "objects" for the iteration
foreach($objects as $object) {
listProperties($object);
}
function listProperties($object)
{
echo 'Properties for Object: ' . get_class($object);
$reflect = new ReflectionClass($object);
$properties = $reflect->getProperties(
ReflectionProperty::IS_PUBLIC +
ReflectionProperty::IS_PROTECTED
);
foreach ($properties as $prop) {
echo $prop->getName() . "\n";
}
}
I have some Json being returned from facebook which I'm then parsing in to an array using json _decode. The data ends up looking like this (this is just the snippet I'm interested in):
( [data] =>
Array ( [0] =>
Array (
[id] => 1336269985867_10150465918473072
[from] =>
Array ( [name] => a name here
[category] => Community
[id] => 1336268295867 )
[message] => A message here
Now I've been able to iterate over this data and get what I need:
$jsonDecoded = json_decode($json, true);
$xmlOutput = '<?xml version="1.0"?><data><items>';
foreach ($jsonDecoded as $e) {
foreach ($e as $i) {
$xmlOutput .= '<item><timestamp>' . $i['created_time'] . '</timestamp><title><![CDATA[ ' . $i['message'] .' ]]></title><link>' . $link . '</link><type>facebook</type></item>';
}
}
$xmlOutput .= '</items></data>';
..up until now where I need to check on the from->id value.
I added this line in the second for each:
foreach ($e as $i) {
if($i['from']['id'] == '1336268295867') {
But this just gives me an error:
Fatal error: Cannot use string offset as an array in /Users/Desktop/Webs/php/getFeeds
Any ideas why? I'm sure this is the correct way to get at that value and in actual fact if I echo this out in my loop instead of doing the if statement above I get the value back:
$jsonDecoded = json_decode($json, true);
$xmlOutput = '<?xml version="1.0"?><data><items>';
foreach ($jsonDecoded as $e) {
foreach ($e as $i) {
echo $i['from']['id']
This returns me all of the from->id values in the code returned from facebook and then following this I get the error:
133626829985867133626829985867133626829985867133626829985867195501239202133626829985867133626829985867133626829985867133626829985867133626829985867
Fatal error: Cannot use string offset as an array in /Users/Desktop/Webs/php/getFeeds.php on line 97
(line 97 is the echo line)
Your code makes a lot of assumptions about $i['from']['id'] and at least one of them is incorrect for at least one entry.
Let's add some tests:
$jsonDecoded = json_decode($json, true);
$xmlOutput = '<?xml version="1.0"?><data><items>';
foreach ($jsonDecoded as $e) {
if ( !is_array($e) ) {
die('type($e)=='.gettype($e).'!=array');
}
foreach ($e as $i) {
if ( !is_array($i) ) {
die('type($i)=='.gettype($i).'!=array');
}
else if ( !array_key_exists('from', $i) ) {
die('$i has no key "from"');
}
else if ( !is_array($i['from']) ) {
die('type($i["from"])=='.gettype($i['from']).'!=array');
}
else if ( !array_key_exists('id', $i['from']) ) {
var_dump($i);
die('$i["from"] has no key "id"');
}
echo $i['from']['id'];
}
}
And then you can add a var_dump(...) before the die(...) to take a look at the actual data.
It seems to me that (according to the last code snippet) at some point your $i is not an array anymore. Try to do:
$jsonDecoded = json_decode($json, true);
$xmlOutput = '<?xml version="1.0"?><data><items>';
foreach ($jsonDecoded as $e) {
foreach ($e as $i) {
if(is_array($i))
echo $i['from']['id']