Need help access like object in php - php

I have this array
$data = array(
'employer' => $employer,
'manager' => $manager
);
my intention is access the array as an object, like: $data->employer.
How can i do that?

You can typecast an array to object like so:
<?php
$data = array(
'employer' => "employer",
'manager' => "manager "
);
$object = (object) $data;
var_dump($object->employer); // => "employer"
The returned value will be an instance of \stdClass, as described in the documentation.

Related

PHP - Read value from Current array

I have an array that looks like this:
$data = array (
"card" => array(
"id" => $_GET["id"],
"user" => dynamicFunction($_GET["id"]),
"Origin" => $data["card"]["user"]
));
I'm getting an error here.
How can I read the value from current array element user without calling dynamicFunction again since that function will execute DB query again. I don't want to overload my SQL server with unnecessary queries.
Thanks in advance!
Option 1:
$user = dynamicFunction($_GET["id"]);
$data = array (
"card" => array(
"id" => $_GET["id"],
"user" => $user,
"Origin" => $user,
));
Option 2:
$data = array (
"card" => array(
"id" => $_GET["id"],
"user" => dynamicFunction($_GET["id"]),
));
$data["card"]['Origin'] = $data["card"]['user'];
Option 3:
$data = array (
"card" => array(
"id" => $_GET["id"],
"user" => $user = dynamicFunction($_GET["id"]),
"Origin" => $user,
));
And no, you cannot access item af array which is not yet initialized.

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

PHP ObjectId group a number of Ids

I have a two collections one of all the people I am following and another of what they have been posting on social networking sites like Twitter and Facebook.
The following collection has a subarray of the _id of the feed collection of each user which each status has the word owner and that has the ObjectId that the owner which is the same as the following key. Here is an example.
'_id' => new MongoId("REMOVED"),
'following' =>
array (
'0' => 'ObjectId("53bf464ee7fda8780c8b4568")',
'1' => 'ObjectId("53b00ab5e7fda8304b8b4567")',
),
'owner' => new MongoId("53b9ea3ae7fda8863c8b4123"),
and in the feed you will see that the following.0 status below
array (
'_id' => new MongoId("REMOVED"),
'owner' => new MongoId("53bf464ee7fda8780c8b4568"),
'status' => ' love this video - Pedigree Shelter dogs http://youtube.com/watch?v=5v5Ui8HUuN8',
'timestamp' => new MongoDate(1405044327, 565000),
)
While I can loop through one by one, I can't for some reason do an $or search. I am not quite understanding how I loop through the following array and add it to the search query before I ran the query.
collection = static::db()->feed;
$where=array( '$or' => array(array('owner' => new MongoId($following.0)))));
$feed = $collection->find($where);
return $feed;
now I understand I will somehow have to loop the $where=array( '$or' => array(array('owner' => new MongoId($following.0))))); But I am just not 100% sure how to do this.
Update
As per the answer below I had to edit the array that was returned - now I have only got this working manually and can't seem to get the PHP script to do it.
Answer Returns
Array ( [owner] => Array ( [$in] => Array ( [0] => new MongoId("53bf464ee7fda8780c8b4568") [1] => new MongoId("53b00ab5e7fda8304b8b4567") ) ) )
Correct:
Array ( "owner" => Array ( '$in' => Array ( "0" => new MongoId("53bf464ee7fda8780c8b4568"), "1" => new MongoId("53b00ab5e7fda8304b8b4567") ) ) )
I am not sure how else to get this to work.
current PHP
$collection = static::db()->following;
$following = $collection->findOne(array ('owner' => new MongoId($_SESSION['user_information'][0]['_id'])));
$follow = $following['following'];
$collection = static::db()->feed;
$where=array("owner" => array( '$in' =>$follow));
print_r($where);
$feed = $collection->find($where);
print_r($feed);
return $feed;
I have fixed a small issue with the collection and now the return array shows
Array ( [owner] => Array ( [$in] => Array ( [0] => MongoId Object ( [$id] => 53bf464ee7fda8780c8b4568 ) [1] => MongoId Object ( [$id] => 53b00ab5e7fda8304b8b4567 ) ) ) )
However, I still can't get it to return the feed like this one:
array (
'_id' => new MongoId("53bf4667e7fda8700e8b4567"),
'owner' => new MongoId("53bf464ee7fda8780c8b4568"),
'status' => ' love this video - Pedigree Shelter dogs http://youtube.com/watch?v=5v5Ui8HUuN8',
'timestamp' => new MongoDate(1405044327, 565000),
)
I am presuming here that this is just a PHPism in the way things are displayed and that your following array is an actual array and not a hash/map, which would generally look like this in a JSON representation:
{
"following": [
ObjectId("53bf464ee7fda8780c8b4568"),
ObjectId("53b00ab5e7fda8304b8b4567"),
],
"owner": ObjectId("53b9ea3ae7fda8863c8b4123"),
}
In which case the "following" is already an actual array, and if you just want to .find() all the "feed" items for the people you are following, then you just pass that to the $in operator for your query selection:
$where = array( "owner" => array( '$in' => $following ) );
$feed = $collection->find($where);
return $feed;
The returned cursor will only contain results from the feed where the "owner" is present in your "following" array from the other collection item.
Watch this code:
$list = array(new MongoId(), new MongoId, new MongoId());
$doc = array( "owner" => array( '$in' => $list ));
echo json_encode( $doc, JSON_PRETTY_PRINT );
Despite how this serializes for JSON by this method the equivalent JSON is:
{
"owner": {
"$in": [
ObjectId("53bf8157c8b5e635068b4567"),
ObjectId("53bf8157c8b5e635068b4568"),
ObjectId("53bf8157c8b5e635068b4569")
]
}
}
That is how the BSON will serialize and is the correct query.
(Answer added on behalf the question author to move it to the answer space).
The issue was fixed when I used the following:
var_dump(iterator_to_array($feed));

Array with colon

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.

PHP - trying to make a JSON-like array and getting confused

I am using PHP and trying to create an array that looks something like this:
{
"aps" : {
"alert" : "Hey"
},
"custom_control" : {
"type" : "topic_comment",
"object":{
"topic_id":"123",
"topic_section":"test"
"plan_id":"456"
}
}
}
So far I have something like
$message = array('aps'=>array('alert'=>$some_variable));
but I am getting confused how I can put the values for "custom_control" into this array after that. Could anyone please advise how to do that from my existing php?
Thanks!
Is this what you mean?
<?php
$some_variable = "Hey";
$myArray = array(
"aps" => array(
"alert" => $some_variable
),
"custom_control" => array(
"type" => "topic_comment",
"object" => array(
"topic_id" => "123",
"topic_section" => "test",
"plan_id" => "456"
)
)
);
?>
Here is an easy way to discover what you need to do.
Create your JSON object.
Use it as input to the json_decode function.
Use the output of this as the input to var_export()
So supposing you assigned your JSON to $json_object, then use:
var_export(json_decode($json_object, true));
If you are more comfortable building the object in JSON you can use the JSON parser included in php. Also, JSON defines Javascript objects, not arrays (although you can define arrays in JSON with something like {myArray : [1,2,3]}
Try this if you want though:
http://php.net/manual/en/function.json-decode.php
If you've already created your initial message array (per your question), you would then do something like this.
$message["custom_control"] = array(
"type" => "topic_comment",
"object" => array(
"topic_id" => "123",
"topic_section" => "test",
"plan_id" => "456"
)
)
You can create whatever nodes you needs inside of $message this way.
What you are trying to create is not an array, but rather an object.
Try to not build it as an array but an object.
$obj = new stdClass();
$obj->aps = new stdClass();
$obj->aps->alert = 'Hey';
$obj->custom_control = new stdClass();
$obj->custom_control->type = 'topic_comment';
$obj->custom_control->object = new stdClass();
$obj->custom_control->object->topic_id = '123';
$obj->custom_control->object->topic_section = 'test';
$obj->custom_control->object->plan_id = '456';
$json = json_encode($obj);
$array = array();
$array['aps'] = "alert";
$array['custom_control'] = array();
$array['custom_control']['type'] = "topic_comment";
$array['custom_control']['object'] = array('topic_id' => '123',
'topic_section' => 'test',
'plan_id' => '456');
i think you need something like this:
$message =array( "aps" =>array("alert"=>"Hey"),
"custom_control" => array(
"type" => "topic_comment",
"object" => array(
"topic_id"=>"123",
"topic_section"=>"test",
"plan_id"=>"456"
)
)
);

Categories