Array with colon - php

SOLVED:
getDimesions() ... google has made a type error.. LOL
facing some problems with array with colon in the name,
my $result is containing
gapiReportEntry::__set_state(array(
'metrics' =>
array (
'uniquePageviews' => 1523,
),
'dimensions' =>
array (
'pagePath' => '/',
'pageTitle' => 'Eventyrgolf',
'source' => 'google',
'medium' => 'organic',
'campaign' => '(not set)',
),
))
gapiReportEntry::__set_state(array(
'metrics' =>
array (
'uniquePageviews' => 210,
),
'dimensions' =>
array (
'pagePath' => '/dk/greenfee-og-banen-8/',
'pageTitle' => 'Greenfee og Banen',
'source' => 'google',
'medium' => 'organic',
'campaign' => '(not set)',
),
))
But some how i cannot get the "dimensions:private"... What to do?
I tried print_r():
$result->{"dimensions:private"}
$result['dimensions:private']
$result->dimensions
Full code:
$ga->requestReportData($profileId, $dimensions, $metrics, $sort, null, $fromDate, $toDate, 2, 30);
foreach ($ga->getResults() as $result) {
print_r($result->dimensions);
}

your $result is not an array, but an object. if you var_dump an object, you see it's contents, which in your case is an object with 2 private variables metrics and dimensions. To access these, the object probably has some accessors:
$result->getMetrics();
$result->getDimensions();

The dimensions property of $result object is private. That means it can be accessed only by objects of the same class.
Check if your gapiReportEntry class contains so called getter, that is a mathod which can access the property dimensions and return it's value to you. Look for something like getDimensions.
Read more about class field visibility here http://pl1.php.net/manual/en/language.oop5.visibility.php
EDIT
If your gapiReportEntry is a google analitics report, then this docs says that there is a getDimensions() method, so just call
$result->getDimensions();
EDIT #2
As suggested in comment, the class seems to have misspeled method name. The actual method is named getDim**es**ions:
$result->getDimesions();

Private is a reserved keyword in PHP and you should be scaping colon ":" with a backslash before it.

Related

PHP - How to dynamically add array to Object request

I am doing Jira REST API calls and I am wondering how I can dynamically add more than one component to the components field using REST API in PHP. I have the following code, works when I set it static, but not sure how to do it dynamically.
Example of static component set:
$data = array(
'fields' => array(
'project' => array(
'key' => $rowAnswers["Key"]
),
'summary' => $rowAnswers["Summary"],
'description' => $rowAnswers["Description"],
'issuetype' => array(
'name' => $rowAnswers["IssueType"]
),
'components' => array(
array(
"name" => "component1"
),
array(
"name" => "component2"
)
)
),
);
My array that I want to replace the static content with:
$components = explode(",", $rowAnswers["Components"]);
$arr = array();
foreach($components as $value){
$array = array("name"=>$value);
array_push($arr,$array);
}
Replacing
'components' => array(
array(
"name" => "component1"
),
array(
"name" => "component2"
)
)
with
'components' => [
$arr
]
doesn't work, I get:
"{"error":false,"error_msg":"","data":"{\"errorMessages\":[],\"errors\":{\"components\":\"expected Object\"}}"}"
I see on an api call to get a request it looks like this:
[components] => Array
(
[0] => stdClass Object
(
[name] => component1
)
[1] => stdClass Object
(
[name] => component2
)
)
But I am unsure how to transform an array into this type of object or request in PHP. Calling with PHP-cURL and json_encoding the data it sends.
Thanks in advance!
you need to decode your json as associative array by setting the second parameter to true
check out the json_decode
assoc
When TRUE, returned objects will be converted into associative arrays.
To fix this I had to do the following:
When creating the array from the DB:
$components = explode(",", $rowAnswers["Components"]);
$arr = array();
foreach($components as $value){
$array = json_decode(json_encode(array("name"=>$value)), FALSE);
array_push($arr,$array);
}
Then to set the component in the request:
'components' => $arr
Thanks

How to cast multiple array elements to object

I'm trying to create an array containing multiple objects.
I wrote this code (it's a member of an existing class)
public static $Roles = [
(object) ['code' => 'SO', 'name' => 'Socio'],
(object) ['code' => 'RESP', 'name' => 'Responsabile zona'],
(object) ['code' => 'AMM', 'name' => 'Amministratore'],
];
but I get this error:
syntax error, unexpected '(object)' (object) (T_OBJECT_CAST),
expecting ')'
on the second line.
I thought this should work, because I already used the same cast syntax to define associative array elements:
return view('edit-headquarter', [
'hq' => (object)['name' => '', 'id' => 0],
'submitAction' => 'insert'
]);
I'm doing something wrong?
EDIT: I'm using PHP 5.4.45
I'm not sure, but this can be related as suggested by Martin Persson
If you're using PHP version below v5.6, then you will not be allowed to have an expression as a default value for class members. Other than that, I don't see anything wrong with the way you have declared it.
To cast an associative array to object you can use a bit dirty, but widely used
$obj = json_decode(json_encode($arr));

Cannot create the JSON response

I'm trying to test a Module and I need to recreate a json as follows:
$billing_info['billing']['source']->exp_year
I tried to recreate it as follows:
$arr = json_encode(['exp_month' => 07, 'funding' => 'credit', 'brand' => 'Visa', 'last4' => '4242']);
$billing_info = [ 'billing' => [ 'source' => $arr ] ];
But I'm not able to call dd($billing_info['billing']['source']->exp_year);
You have to decode your json string before you can access object variables again:
dd(json_decode($billing_info['billing']['source'])->exp_month);
If you really need to create an object as described, you can do the following:
$arr = json_encode(['exp_month' => 07, 'funding' => 'credit', 'brand' => 'Visa', 'last4' => '4242']);
$billing_info = [ 'billing' => [ 'source' => json_decode($arr) ] ];
And than you can call your
dd($billing_info['billing']['source']->exp_month);
method. In the example you described, there is no need to encode/decode to json anyway, but I assume you receive your json string from somewhere else.
json_encode creates a string, not an object, so you can't access properties of it. You have to call json_decode first:
dd(json_decode($billing_info['billing']['source'])->exp_year);
See also json_encode and json_decode docs.
You can also cast the array to object, like that:
$arr = (object) array('exp_month' => 07, 'funding' => 'credit', 'brand' => 'Visa', 'last4' => '4242');
You can then access its properties like that:
var_dump($arr->exp_month);

Storing the full location of an element in a multidimensional array for reuse

This question is based on my other question here about a suitable array processing algorithm.
In my case, I want to flatten a multidimensional array, but I need to store the full key to that element for reuse later.
For example :
array(
0 => array(
'label' => 'Item1',
'link' => 'http://google.com',
'children' => null
)
1 => array(
'label' => 'Item2',
'link' => 'http://google.com',
'children' => array( 3 => array(
'label' => 'SubmenuItem1',
'link' => 'http://www.yahoo.com',
'children' => null
)
)
)
2 => array(
'label' => 'Item3',
'link' => 'http://google.com',
'children' => null
)
)
Should be flattened into something like the following table
Key Link
===================================
[0] http://google.com
[1] http://google.com
[2] http://google.com
[1][3] http://yahoo.com
The problem is that I while I can easily store the location of an element in a multidimensional array, I am finding it to be quite hard to retrieve that element later. For example, if I store my key as $key = "[1][3]", I can not access it using $myarray[$key]. Is there anyway to do this?
Solution using recursion:
//Array parts should be an array containing the keys, for example, to address
//SubmenuItem1, I had 1.3 when the array was flattened. This was then exploded() to the array [1, 3]
$this->recurseIntoArray($myArray, $arrayParts);
private function recurseIntoArray(&$array, $arrayParts){
$current = $arrayParts[0];
$array[$current]['blah'] = 'blah'; //If you want to update everyone in the chain on the way down, do it here
array_shift($arrayParts);
if (!empty($arrayParts)){
$this->recurseIntoArray($array[$current]['children'], $arrayParts);
}else{
//If you want to update only the last one in the chain, do it here.
}
}

PHP / Mongo: how do you update nested data?

I've been playing around with Mongo for about a week now and I still can't work out how to modify nested arrays in Mongo with php.
So here is a sample document...
array (
'_id' => new MongoId("4cb30f560107ae9813000000"),
'email' => 'mo#maurice-campobasso.com',
'firstname' => 'Maurice',
'lastname' => 'Campobasso',
'password' => 'GOD',
'productions' =>
array (
0 =>
array (
'title' => 'a',
'date' => '1286811330.899',
),
1 =>
array (
'title' => 'b',
'date' => '1286811341.183',
),
2 =>
array (
'title' => 'c',
'date' => '1286811350.267',
),
3 =>
array (
'title' => 'd',
'date' => '1286811356.05',
),
),
)
What I wan't to do is delete an array inside the productions array, but I can't work out how. I've been playing with 'update('$pull' => ...etc)' but I haven't been able to make it work.
OK, there are a few ways to do this. In your case, I would do something like
mymongoobject.update( $unset : { "productions.2" : 1 } }
That's basically saying to unset the ".2" element of productions. Some docs here.
Now $pull should also work, but it's a little tougher because "productions" is actually an array of arrays (or objects with sub-objects). So you'd have to match arrays exactly:
mymongoobject.update( $pull : { "productions" : {'title':'d', 'date':'1286811356.05'} }
In the case above, the unset is probably the easiest option (though it will leave a "hole" in the array)
That is actually very easy, unlike traditional sql stuff you just modify the whole data and pass it back.
$cursor = $mongo->yourDB->yourCollection->findOne("_id",4cb30f560107ae9813000000);
//let's remove last item on productions
array_splice($cursor["productions"],2);
//and update the mongo document
echo $mongo->yourDB->yourCollection->update($cursor);
//it echoes 1 if successful
hope it helps.

Categories