I get the response below from a script, and I need to extract board, model, serial number, current and upgrade.
Net\Response Object
(
[unrecognizedWords:protected] => Array
(
)
[_type:Net\Response:private] => !re
[attributes:protected] => Array
(
[board] => true
[model] => CRD
[serialnumber] => XXXXXXXX
[current] => 5.11
[upgrade] => 5.11
)
[_tag:Net\Message:private] =>
)
I've multiple combinations such as this:
echo unrecognizedWords:protected->attributes:protected->board;
However I can not get the values our of the array.
Can someone help me?
You cann't get any protected or private properties of object (only public). Use public methods (getters) of this object (sure, that it's provided).
Read: PHP: Visibility
Related
I have my code in PHP which is returning this Array of data:
GoCardlessPro\Core\ListResponse Object
(
[records] => Array
(
[0] => GoCardlessPro\Resources\Mandate Object
(
[model_name:protected] => Mandate
[created_at:protected] => 2017-04-01T16:49:09.642Z
[id:protected] => ID001
[links:protected] => stdClass Object
(
[customer_bank_account] => CB001
[creditor] => CR001
[customer] => CU001
)
[metadata:protected] => stdClass Object
(
)
[next_possible_charge_date:protected] => 2017-04-06
[payments_require_approval:protected] =>
[reference:protected] => RE001
[scheme:protected] => bacs
[status:protected] => active
[data:GoCardlessPro\Resources\BaseResource:private] => stdClass Object
(
[id] => 123
[created_at] => 2017-04-01T16:49:09.642Z
[reference] => RE001
[status] => active
[scheme] => bacs
[next_possible_charge_date] => 2017-04-06
[payments_require_approval] =>
[metadata] => stdClass Object
(
)
[links] => stdClass Object
(
[customer_bank_account] => 001
[creditor] => CR001
[customer] => CU001
)
)
[api_response] =>
)
)
)
I want to be able to read the ID of the first item in therecords array.
This data is contained inside a variable called $GC_Mandate;
I have tried these:
echo $GC_Mandate->records->{0}->id;
echo $GC_Mandate->records->0->id;
echo $GC_Mandate->records->[0]->id;
$GC_Mandate = $GC_Mandate->records;
echo $GC_Mandate->{0}->id;
But none will return the data
To get the first record, the syntax you need is $GC_Mandate->records[ 0 ].
However, that object is a GoCardlessPro\Resources\Mandate object and its member id is protected1, so we'd need to know the interface of GoCardlessPro\Resources\Mandate (its public methods1), to know if we can somehow retrieve the value of id.
My guess would be getId(), so the full syntax would become
$GC_Mandate->records[ 0 ]->getId()
But, that's just a guess. You'd have to look into the documentation/class definition of GoCardlessPro\Resources\Mandate, to be sure if you can retrieve id.
Turns out (provided I'm linking to the correct github repository) you can do:
$GC_Mandate->records[ 0 ]->id
since GoCardlessPro\Resources\Mandate extends GoCardlessPro\Resources\BaseResource, which exposes the protected members through GoCardlessPro\Resources\BaseResource::__get()2.
1. visibility in PHP
2. magic methods in PHP
I can't comment so I guess I'll have to post.
You should try to print_r($GC_Mandate); and see what it gives out and then go from there.
Try $GC_Mandate->records[0]->__get('id')
it will return all data ..for perticulat data put this in foreach loop
print_r($GC_Mandate['records']);
In my ORM code I have an Entity with a field fined like so:
//part of entity class Item:
/** #Column(name="product_id", type="integer") */
private $productId;
I then executed this code:
//3 lines ~straight out of Doctrine configuration to get EntityManager
include 'config/doctrine-config.php';
$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
$em = EntityManager::create($dbParams, $config);
//my own code to retrieve an entity instance:
$instance = $em->find(Item::class, 2);
print_r($instance);
And this is the output I get (skipping few other similar properties):
Application\Entity\Item Object
(
[id:Application\Entity\Item:private] => 2
[description:Application\Entity\Item:private] => Product Kit
[productId:Application\Entity\Item:private] => -1
)
Note how there are 6 (six) lines above that came out of print_r() function.
And everything was fine, Until
Next, I have changed the $productId column to ManyToOne Relationship on my Item Entity class, like so:
/**
* #ManyToOne(targetEntity="Product", inversedBy="id")
* #JoinColumn(name="product_id", referencedColumnName="id")
*/
private $productId;
I ran the same code.
OUT CAME THE UNIVERSE OF 2,392,600 LINES, WHAT?
Two million, three hundred and ninety two thousand, six hundred lines lines of print_r output.
looking at the print-out I see that DoctrineProxies\__CG__\Application\Entity\Product Object contains 2,392,564 lines printed by print_r
Question:
What is exactly in this object and why is it so big as to take up nearly 300Mb of disk space when printed out?
I cannot help but wonder if such complexity is apt to cause performance issues in every-day code. For example, I am not printing out the contents of the $instance variable in my every-day code, but I surely return the humongousness from a method call. Does that mean it is a 300Mb variable that gets passed from i.e. the $em->find(Item::class, 2); call above?
(Very) Partial Listing
Application\Entity\Item Object
(
[id:Application\Entity\Item:private] => 2
[description:Application\Entity\Item:private] => Product Kit
[ProductId:Application\Entity\Item:private] => DoctrineProxies\__CG__\Application\Entity\Product Object
(
[__initializer__] => Closure Object
(
[static] => Array
(
[entityPersister] => Doctrine\ORM\Persisters\Entity\BasicEntityPersister Object
(
[class:protected] => Doctrine\ORM\Mapping\ClassMetadata Object
(
[name] => Application\Entity\Product
[namespace] => Application\Entity
[rootEntityName] => Application\Entity\Product
[inheritanceType] => 1
[generatorType] => 5
[fieldMappings] => Array
(
[id] => Array
(
[fieldName] => id
[type] => integer
[scale] => 0
[length] =>
[unique] =>
[nullable] =>
[precision] => 0
[columnName] => id
[id] => 1
)
[fieldNames] => Array
(
[id] => id
[description] => description
)
[columnNames] => Array
(
[id] => id
[description] => description
)
[idGenerator] => Doctrine\ORM\Id\AssignedGenerator Object
[reflClass] => ReflectionClass Object
(
[name] => Application\Entity\Product
)
[namingStrategy:protected] => Doctrine\ORM\Mapping\DefaultNamingStrategy Object
[instantiator:Doctrine\ORM\Mapping\ClassMetadataInfo:private] => Doctrine\Instantiator\Instantiator Object
)
[conn:protected] => Doctrine\DBAL\Connection Object
(
[_conn:protected] => Doctrine\DBAL\Driver\PDOConnection Object
(
)
[_config:protected] => Doctrine\ORM\Configuration Object
(
[_attributes:protected] => Array
(
[metadataCacheImpl] => Doctrine\Common\Cache\ArrayCache Object
(
[data:Doctrine\Common\Cache\ArrayCache:private] => Array
(
[dc2_b1e855bc8c5c80316087e39e6c34bc26_[Application\Entity\Item$CLASSMETADATA][1]] => Array
(
[0] => Doctrine\ORM\Mapping\ClassMetadata Object
(
[name] => Application\Entity\Item
[namespace] => Application\Entity
[rootEntityName] => Application\Entity\Item
[customGeneratorDefinition] =>
[customRepositoryClassName] =>
[isMappedSuperclass] =>
[isEmbeddedClass] =>
[parentClasses] => Array
[BAZILLION LINES redacted for brevity]
You can't dump a proxy object without XDebug or similar tools (which limit the dumped object size).
The problem is really, really simple:
Proxy -> references EntityManager -> references UnitOfWork -> contains Proxy
This obviously leads to a recursive data-structure dump, which in turn leads to a mess any time you try to dump it without sensible limits.
DoctrineProxies\__CG__\Application\Entity\Product
is a proxy class... which means that doctrine doesn't actually fetch the entity from the database (for performance) unless it is needed (i.e. calling $product->getName() those proxy Classes are in a recursive loop with eachother and are VERY large as you saw... most of the information there you don't really need unless you are diving deep ... you should never use print_r ... in the new symfony 2.7+ i think there is a function called dump() in debug mode ... if you use that to print the entity it has loop protection and it just shows reference numbers ... you can also use the \Doctrine\Common\Util\Debug::dump() that also will print out a smaller list than 2^234234234 lines ...
I'm querying an API and getting a response back with various countries. Here is the relevant array I'm working with and what it prints out.
print_r($apiResponse['response']['data'][0]['countries']);
prints this:
Array ( [US] => Array ( [id] => 840 [code] => US [name] => United States [regions] => Array ( ) ) [CA] => Array ( [id] => 124 [code] => CA [name] => Canada [regions] => Array ( ) ) )
I am looking to save an array of only the two character country codes from that data. The only thing is the key is unknown to me when I query it so I don't know how to access the [code] section of it to save it to my new array.
I want to end up being able to take whatever amount of countries the API sends back and save the two character codes in a format like this:
'country_codes' => array('US','CA','UK','AU')
Thanks for your help!
Use the array_keys() function. Here you have the documentation.
array(
[key] => Array
(
[229] => Tuple Object
(
[ID] => 1
[NAME] => abc
)
[233] => Tuple Object
(
[ID] => 2
[NAME] => abcd
)
...
...
...
)
[moreinfo] = 'xyz'
)
issue is when i am using json_encode tuple object is getting lost as all data types like id,name are private.
Following Solution i have found
change private variables to public, still i can access the variables as array instead of objects :-(
write a wrapper which convert object to array...... an extra effort
can any one suggest a solution in which i can use objects.
I've seen similar questions on here but I can't seem to apply the solutions to my problem. I have a variable called $results which I got from an API. I'll change the proper nouns so as to protect my work's customers:
stdClass Object
(
[out] => stdClass Object
(
[count] => 2
[transactions] => stdClass Object
(
[RealTimeCommissionDataV2] => Array
(
[0] => stdClass Object
(
[adId] => 12345678
[advertiserId] => 123456789
[advertiserName] => Chuck E. Cheese, inc.
[commissionAmount] => 50
[country] => US
[details] => stdClass Object
(
)
[eventDate] => 2009-11-16T09:44:25-08:00
[orderId] => X-XXXXXXXXXX
[saleAmount] => 0
[sid] => 123456789
[websiteId] => 2211944
)
[1] => stdClass Object
(
[adId] => 987654321
[advertiserId] => 12345
[advertiserName] => Chorizon Wireless.
[commissionAmount] => 50
[country] => US
[details] => stdClass Object
(
)
[eventDate] => 2009-11-16T09:58:40-08:00
[orderId] => X-CXXXXXX
[saleAmount] => 0
[sid] => 61-122112
[websiteId] => 1111922
)
)
)
)
)
I shortened it to two entries here but the number of entries will vary, it's the result of a check for transactions in the past hour, there may sometimes be only one and sometimes as many as a dozen.
I want to assign these entries to variables like websiteId1 websiteId2 etc. I know I need to do a foreach loop but can't seem to figure it out. How can I write it so that I get the "[details]" as well?
foreach ($results->out->transactions->RealTimeCommissionDataV2 AS $commissionData) {
// you can access the commissionData objects now, i.e.:
$commissionData->adId;
$commissionData->details;
}
<?
foreach ($result->out->transactions->RealTimeCommissionDataV2 as $item)
{
// do somthing with each item.
print_r($item);
// or the details array
$num_details = sizeof($item->details)
}
I think this is what you want.
EDIT
Updated based on some notes in the documentation. Specifically, these two
a numerically indexed array will not
produce results unless you use
EXTR_PREFIX_ALL or
EXTR_PREFIX_INVALID.
Prefixes are automatically separated
from the array key by an underscore
character.
echo extract( $results->out->transactions->RealTimeCommissionDataV2, EXTR_PREFIX_ALL, 'websiteId' );
// test the extract
print_r( $websiteId_0 );