PHP convert Array to Object - php

var_dump($response);
outputs:
array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32616923206) ["namespace"]=> string(7) "ly26638" } } }
array(1) { ["metafields"]=> array(1) { [13]=> array(10) { ["id"]=> int(32641864774) ["namespace"]=> string(7) "ly26638" } } }
how can I convert $response to an object to operate it like in the following code:
echo $response->metafields[0]->id;
I've tried the code below, but without any result :/
$object = json_decode(json_encode($response));

If you want to access your "metafields's id" like $response->metafields[13][id] then you need to cast your response array to object.
Ex.
$response = (object) array(
'metafields' => array(
'13' => (object) array(
'id' => 32616923206,
'namespace' => "ly26638"
)
)
);
Then you can use syntax like $response->metafields[13]->id to access the "id" value.

If you make an object with (object) $response, the child elements will still be arrays. Then you could do
$response->metafields[13][id]
If you want the object notation through the whole chain you need something like the function sandip has provided.
But why not just make this call:
$response[metafields][13][id]

You can't find the member of an object by '[]'.
The '[]' is for arrays, and the '->' is for objects.
So the reason for the blank output is: metafields[0].
The code below is wrong:
echo $response->metafields[0]->id;
So you should change the key of the array, the key of an array should not be a pure number.
I tried to change the key to 'a13', and with the code of:
echo $response->metafields->a13->id;
I got "32616923206".
That's all. O(∩_∩)O~

Related

How to store associative array in Laravel

I'm new to Laravel, and I want to store this array in DB.
This is the php code of my array:
$socialNetwork = array();
$socialNetwork[0]["name"]= "Facebook";
$socialNetwork[0]["account"]= "facebook_account";
$socialNetwork[1]["name"]= "Twitter";
$socialNetwork[1]["account"]= "twitter_account";
$socialNetwork[2]["name"]= "Instagram";
$socialNetwork[2]["account"]= "insta_account";
The var_dump() looks like this:
array(3) {
[0] => array(2) {
["name"] => string(8) "Facebook"
["account"] => string(16) "facebook_account"
}
[1] => array(2) {
["name"] => string(7) "Twitter"
["account"] => string(15) "twitter_account"
}
[2] => array(2) {
["name"] => string(9) "Instagram"
["account"] => string(13) "insta_account"
}
}
I've tried several things but I can't get it to work!
Please help with the code. The table name is socialAccounts
Add a column in your database for this field; a JSON or TEXT type will do the job.
Next, you should add the column to the $casts array on your SocialAccount model:
protected $casts = [
'facebook_account' => 'array',
];
Now, whenever you retrieve this value, it will be deserialized for you.
To store the value, just use json_encode():
$social_account->facebook_account = json_encode($facebookArrayData);
$social_account->save();
You can read more on attribute casting in the docs; https://laravel.com/docs/7.x/eloquent-mutators#attribute-casting

Make multidimensional array with php and pdo

i want to edit a script i found online. is has an hardcoded array like this.
$servers = array(
'Google Web Search' => array(
'ip' => '',
'port' => 80,
'info' => 'Hosted by The Cloud',
'purpose' => 'Web Search'
),
'Example Down Host' => array(
'ip' => 'example.com',
'port' => 8091,
'info' => 'ShittyWebHost3',
'purpose' => 'No purpose'
)
);
Result:
array(2) {
["Google Web Search"]=>
array(4) {
["ip"]=>
string(0) ""
["port"]=>
int(80)
["info"]=>
string(19) "Hosted by The Cloud"
["purpose"]=>
string(10) "Web Search"
}
["Example Down Host"]=>
array(4) {
["ip"]=>
string(11) "example.com"
["port"]=>
int(8091)
["info"]=>
string(14) "ShittyWebHost3"
["purpose"]=>
string(10) "No purpose"
}
}
I put this data in a database and want to make the same array but i dont seem to get it working
This is the code i added to make an array:
$query ="SELECT name, ip, port, hosting FROM sites";
$select = $conn->prepare($query);
$select->execute(array());
$testing = array();
while($rs = $select->fetch(PDO::FETCH_ASSOC)) {
$testing[] = array($rs['name'] => array('ip'=> $rs['ip'], 'port'=> $rs['port'], 'hosting'=> $rs['hosting']));
}
The result from this is:
array(2) {
[0]=>
array(1) {
["Google Web Search"]=>
array(3) {
["ip"]=>
string(10) "google.com"
["port"]=>
string(2) "80"
["hosting"]=>
string(19) "Hosted by The Cloud"
}
}
[1]=>
array(1) {
["Example Down Host"]=>
array(3) {
["ip"]=>
string(11) "example.com"
["port"]=>
string(2) "09"
["hosting"]=>
string(14) "ShittyWebHost3"
}
}
}
is there a way to make the bottom array the same as the top array, i dont want to edit the whole script, this seems easier.
You are appending a new integer indexed element with [] and then adding 2 nested arrays. Instead, add the name as the key:
$testing[$rs['name']] = array('ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']);
Since you specify the columns in the query and they are the same as the array keys, then just this:
$testing[$rs['name']] = $rs;
When you assign a value to an array you use the syntax $arr[key] = $value. If you omit the key during the assignment, $value will be assigned to the next available integer key of the array, starting from 0.
This is an example of how it works:
$arr = array();
$arr[] = 'one';//Empty, so insert at 0 [0=>'one']
$arr[] = 'two';//Last element at 0, so use 1 [0=>'one',1=>'two']
$arr[6]= 'three';//Key is used, so use key [0=>'one',1=>'two',6=>'three']
$arr[] = 'four';//Max used integer key is 6, so use 7
print_r($arr);//[0=>'one',1=>'two',6=>'three',7=>'four']
So, when in your code you are using
$testing[] = array(
$rs['name'] => array(
'ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']
)
);
You are assigning the newly created array to the positions 0,1,2,..N.
To avoid this, just specify the key explicitly, using the value you really want, like
$testing['name'] => array(
'ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']
);
You can read more about arrays in the documentation
Side note
If you don't mind having an extra column in the generated arrays, you can rewrite entirely your code this way:
$query ="SELECT name, ip, port, hosting FROM sites";
$results = $conn->query($query)->fetchAll(PDO::FETCH_ASSOC);
$testing = array_column($results,null,'name');
It's slightly slower, but very handy in my opinion, PDOStatement::fetchAll retrieves all the data at once and array_column using null as second parameter does reindex the array with the wanted column as key.
PDOStatement::fetchAll
array_column

Strange stdClass as array error when the variable seems to be an array, not an object

Something I noticed which patches the problem:
If I return $this->_data instead of $this->_data[0] - and then use $object->data()[0], it does work as expected... However, I would like to return the [0] in the function.
Before you start saying that this is a duplicate - this question is unlike most other questions regarding this error.
I'm getting the following error when trying to access $this->_data[0] in my class:
Cannot use object of type stdClass as array
This is the function/line the error is being triggered on:
public function data(){
return $this->_data[0]; //<- line 75
}
To my understanding, this error occurs when I try to use an object as I would use an array. However, when I var_dump($this->_data), I get the following result:
array(1) {
[0]=> object(stdClass)#34 (10) {
["uid"]=> string(1) "0"
["nid"]=> string(3) "374"
["id"]=> string(8) "YicnaxYw"
["txt_content"]=> NULL
["path"]=> string(32) "/uploads/images/png/YicnaxYw.png"
["image"]=> string(1) "1"
["timestamp"]=> string(10) "1448192959"
["file_ext"]=> string(3) "png"
["file_type"]=> string(9) "image/png"
["originalFilename"]=> string(23) "2015-11-22_12-49-17.png"
}
}
Where clearly this variable is of type array(1) with a [0] element ..
Could someone tell me what I'm doing wrong?
Thanks in advance.
#Xeli $this->_data[0]->nid causes the same error
Fatal error: Cannot use object of type stdClass as array in /home3/ramzes/includes/classes/UploadItem.php on line 75
UploadItem.php:75
public function data(){
return $this->_data[0]->nid;
}
$this->_data[0] is a fetchAll(PDO::FETCH_OBJ) object with the results from the query
EDIT:
I've set up a test for this at http://ideone.com/66I3wO - I'm storing your object in an array and I can access $this->_data[0]->nid just fine.
<?php
class Test
{
public $_data = [];
public function __construct() {
$this->_data[0] = (object) [
'uid' => '0',
'nid' => '374',
'id' => 'YicnaxYw',
'txt_content' => null,
'path' => '/uploads/images/png/YicnaxYw.png',
'image' => '1',
'timestamp' => '1448192959',
'file_ext' => 'png',
'file_type' => 'image/png',
'originalFilename' => '2015-11-22_12-49-17.png'
];
}
public function data(){
return $this->_data[0];
}
}
$test = new Test();
echo $test->_data[0]->nid;
var_dump( $test->data() );
I think the PDO returns an object which is implemented via something like this: http://php.net/manual/en/class.iteratoraggregate.php
When you var_dump it, it will look like an array, but it's not.
You could change your data function to this:
function data() {
foreach($this->_data as $data) {
return $data;
}
}
If you explicitly convert to array then you can access the index like you want to:
$return = (array) $this->_data;
return $return[0];

Push Associate array into another array

I would like to push an associate array into another array but I an not sure how to go about it. At the minute I have the following:
$rate_info = array(
"hotel_rating" => $hotel->{'hotelRating'},
"room_rate" => $hotel->{'RoomRateDetailsList'}->{'RoomRateDetails'}->{'RateInfo'}->{'ChargeableRateInfo'}->{'#total'},
"currency" => $hotel->{'RoomRateDetailsList'}->{'RoomRateDetails'}->{'RateInfo'}->{'ChargeableRateInfo'}->{'#currencyCode'},
"deep_link" => $hotel->{'deepLink'}
);
array_push($hotel_array[$hotel->{'name'}]["offers"], "expedia" => $rate_info );
"Offers" is an array , all I want to do is add an key value with an array within in. Any ideas? All I seem to be getting at the minute is parse errors.
UPDATE
This is the output of the array so far
["offers"]=>
array(2) {
["LateRooms"]=>
array(4) {
["hotel_rating"]=>
int(4)
["room_rate"]=>
string(6) "225.06"
["currency"]=>
string(3) "USD"
}
[0]=>
string(4) "test"
}
As you can see instad of [0] I would like ["site"]=>array()
Thanks
Oliver
I'd do this for the array assignment:
$hotel_array[$hotel->name]['offers']['expedia'] = $rate_info;
Ensure your warnings are enabled, so you know arrays (and subarrays) have been set up before you use them.
Did you first do this?
$hotel_array[$hotel->{'name'}] = array();
And then you can do:
array_push($hotel_array[$hotel->{'name'}]["offers"], "expedia" => $rate_info );

Get specific key value pair from multidimensional array

I have the following array:
array(2) {
[0] => array(3) {
["submission_id"] => int(28)
["date"] => string(22) "2010-10-18 15:55:33+02"
["user_id"] => int(12)
}
[1] => array(3) {
["submission_id"] => int(37)
["date"] => string(22) "2010-11-21 16:02:07+01"
["user_id"] => int(23)
}
I want to get only the user_id key values from this array. I could obviously loop over it, but I was wondering if there was a quicker way.
You could use array_map (might not be quicker though, as it will make a function call per array element):
function getUserId($a) {
return $a['user_id'];
}
$user_ids = array_map('getUserId', $array);
Apart from that, looping is the only way (array_map makes loop anyway).
You can access only the user_id values like this if you know the array index you want to access:
$arr = your array here..
echo $arr[0]['user_id'];
echo $arr[1]['user_id'];

Categories