Cannot create the JSON response - php

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);

Related

How to expand a dot notation array into a full multi-dimensional array

In my Laravel project, I have a dot notation array which I need to convert to a multi-dimensional array.
The array is something like this:
$dotNotationArray = ['cart.item1.id' => 15421a4,
'cart.item1.price' => '145',
'cart.item2.id' => 14521a1,
'cart.item2.price' => '1245'];
How can I expand it to an array like:
'cart' => [
'item1' => [
'id' => '15421a4',
'price' => 145
],
'item2' => [
'id' => '14521a1',
'price' => 1245,
]
]
How can I do this?
In Laravel 6+ you can use Arr::set() for this:
The Arr::set method sets a value within a deeply nested array using "dot" notation:
use Illuminate\Support\Arr;
$multiDimensionalArray = [];
foreach ($dotNotationArray as $key => $value) {
Arr::set($multiDimensionalArray , $key, $value);
}
dump($multiDimensionalArray);
If you are using Laravel 5.x you can use the array_set() instead, which is functionally identical.
Explanation:
Arr::set() sets value for a key in dot notation format to a specified key and outputs an array like ['products' => ['desk' => ['price' => 200]]]. so you can loop over your array keys to get a multidimensional array.

Getting a value from associative arrays PHP

I have an array..
$file=array(
'uid' => '52',
'guarantee_id' => '1116',
'file_id' => '8',
'file_category' => 'test',
'meta' =>'{"name":"IMAG0161.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpzdiaXV","error":0,"size":1749244}',
'FileStorage' => array()
)
and I am trying to extract the name using
$fileName = $file['meta'['name'];
which gives me a Illegal string offset 'name' error.
The value of $file['meta'] is a string, not an array. That means your approach to access the value does not work.
It looks like that meta value string is a json encoded object. If so you can decode it and then access the property "name" of the resulting object.
Take a look at this example:
<?php
$file = [
'uid' => '52',
'guarantee_id' => '1116',
'file_id' => '8',
'file_category' => 'test',
'meta' =>'{"name":"IMAG0161.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpzdiaXV","error":0,"size":1749244}',
'FileStorage' => []
];
$fileMeta = json_decode($file['meta']);
var_dump($fileMeta->name);
The output obviously is:
string(12) "IMAG0161.jpg"
In newer version of PHP you can simplify this: you do not have to store the decoded object in an explicit variable but can directly access the property:
json_decode($file['meta'])->name
The output of this obviously is the same as above.
This is happening because your meta is a json, so you should decode and then access whatever you need, not that I placed true as second parameter becuase i wanted to decode as an associative array instead of an object
$decoded = json_decode($file['meta'],true);
echo $decoded['name'];
//print IMAG0161.jpg
You can check a live demo here
But you can easily access as an obect
$decoded = json_decode($file['meta']);
echo $decoded->name;
//print IMAG0161.jpg
You can check a live demo here
<?php
$file=array(
'uid' => '52',
'guarantee_id' => '1116',
'file_id' => '8',
'file_category' => 'test',
'meta' =>'{"name":"IMAG0161.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpzdiaXV","error":0,"size":1749244}',
'FileStorage' => array()
);
$meta=$file['meta'];
$json=json_decode($meta);
echo $json->name;
?>

change value of a key of an array within an array in php?

I have an array within an array like:
$some_large_array = array(
'person' => array('name' => 'stefanie', 'hobby' => 'rock climbing',),
'dog' => array('name' => 'orbit', 'hobby' => 'chewing curtains'));
How can I change the value of of 'hobby' of 'dog' and return it as 'napping'?
You can access array keys like this, in your example:
$some_large_array['dog']['hobby'] = 'napping';
(answering to remove from "unanswered" queue)

Using square brackets and assigning variables in PHP

I have seen source code like:
$something = $sql['value']
I have searched a lot about it and I found that it's from arrays. But I didn’t understand the exact meaning.
For example,
$people = [
'Susan' => [
'Age' => 24,
'Phone' => '555-123-4567'
],
'Jack' => [
'Age' => 27,
'Phone' => '555-9876-5432'
]
];
echo $people['Jack']['Age']; // 27
Can we write code like the following?
if(!empty($people)
$something = $people['a value']
I just need to know how we can declare a variable and give a value in square brackets.
If you are using $something = $people['a value'] it means you are assigning a value of the $people array having an index of a value.
So you don't have that and so it will throw you undefined index error.
You are using a nested associative array and you have to output using something like:
echo $people['Jack']['Age'];
As you wanted a brief example, say you have an array like
$people = array('name'=>'Jack');
Now, when you want to store the name in a variable, you use
$store_name = $people['name'];
echo $store_name; // Echoes "Jack"
Try this:
$people = array(
'Susan' => array('Age' => 24, 'Phone' => '555-123-4567'),
'Jack' => array('Age' => 27, 'Phone' => '555-9876-5432')
);
You can use array and write it like this
$people = array(
'Susan' => array(
'Age' => 24,
'Phone' => '555-123-4567'
),
'Jack' => array(
'Age' => 27,
'Phone' => '555-9876-5432'
)
);
echo $people['Jack']['Age']; // 27
if(!empty($people)
$something = $people['a value']
Square brackets mean index, so $people['a value'] is a value that lays under the 'a value' index of the $people array.
Square brackets are also used as a shortcut for array().. See it here-

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.

Categories