How would I go about accessing these elements from a Shopify JSON in PHP
JSON:
{
"orders":[
{ "note_attributes":[
{
"name":"field1",
"value":"xxxxxxxxxxxx"
},
{
"name":"field2",
"value":"xxxxxx"
},
{
"name":"field3",
"value":"xxxxxx"
}
],
This is just snippet of the object. How would I access each value and assign it to the name? Eg this $req['account_id'] would equal the value for that name tag. This is how am trying to do it but it's not working:
foreach ($order['note_attributes'] as $attributes) {
$req = array();
$req[$attributes->name] = $attributes[$attributes->value];
}
I would then like to echo $req['account_id'] and that would = xxxxxxxxx#gmail.com but it's not working any suggestions or fixes?
When iterating over Objects properties, one approach is to use (as you have) foreach
// accessing property
foreach ($objects as $object) {
echo $object->property;
}
// accessing key-value pair
foreach ($object as $key => $value) {
echo "$key => $value\n";
}
An example:
$attributes = array();
.
.
foreach($note_attributes as $note_attribute) {
$key = $note_attribute['name'];
$value = $note_attribute['value'];
$attributes[$key] = $value;
}
The structure should be in key-value pairs. ie.
attributes [
"account1234" => "abc#xxx.com",
"account_password" => "asdasdasd"
]
Hope this helps.
Update: as Roopendra mentioned, json_decode() with a TRUE flag with return an associative array, else stdClass.
Related
I have a multi-dimensional array with key value pairs. Some of the values of the keys are arrays, and some of the values in that array are arrays as well. It is only 3 branches deep (for now), but I am trying to recursively loop through the array, save the key for each level of the branch, and create a new array when it reaches a string that also mimics the structure of the original array. When it reaches a string, there should be a new object instantiation for each value.
The code below sort of does this, but only creates a flat array.
foreach ($data as $key => $value) {
if (!is_array($value)) {
$a_objects[$key] = new Component([$key], $value);
} else {
foreach ($value as $valueKey => $valueValue) {
if (!is_array($valueValue)) {
$a_objects[$key . "_" . $valueKey] = new Component([$key, $valueKey], $valueValue);
} else {
foreach ($valueValue as $k => $v) {
$a_objects[$key . "_" . $valueKey . "_" . $k] = new Component([$key, $valueKey, $k], $v);
}
}
}
}
Here is my own best attempt at this but it does not seem to save into the b_objects after some testing it does not seem to be saving the object instances.
$b_objects = [];
function create_r($data, $id)
{
foreach ($data as $key => $value) {
if (is_array($value) == true) {
array_push($id, $key);
create_r($value, $id);
} else {
array_push($id, $key);
$b_objects[$key] = new Component($id, $value);
$id = [];
}
}
}
$id = [];
create_r($data, $id);
echo "this is b_objects";
echo "<pre>";
print_r($b_objects);
echo "</pre>";
I verified that $id array contains the right "keys". I feel like this solution is pretty close but I have no idea how to use my $id array to mimic the structure of the $data.
I want to be able to say $b_objects[$level1key][$level2key][$level3key]...[$leveln-1key] = new Component...
Thanks!
I suggest you pass $b_objects by reference to your create_r() function. Otherwise each function call will instantiate a new $b_objects variable which is not used anywhere in the code afterwards.
Passing by reference allows the function to actually change the input array. Notice the & sign in the function declaration.
function create_r($data, $id, &$res)
{
foreach ($data as $key => $value) {
if (is_array($value) == true) {
array_push($id, $key);
create_r($value, $id, $res);
} else {
array_push($id, $key);
$res[$key] = new Component($id, $value);
$id = [];
}
}
}
$id = [];
$b_objects = [];
create_r($data, $id, $b_objects);
so lets say i have a object like this
{
"status": "AlreadyVerified"
}
and i want to store propert key in variable so i can access property using that variable like
$key = 'status';
echo $object->$key
but what if i have a nested object like
{
"extra_info": {#305 ▼
+"status": "AlreadyVerified"
}
}
this wouldn't work
$key = 'extra_info->status';
echo $object->$key
how can i store nested object chain in a variable so i can access its property using that variable ?
preferably some way that works for both nested and flat objects (i guess that's what the're called !)
It can be possible by write helper function like this:
function deepFind($o, $key) {
$key = explode('->', $key);
$value = $o;
foreach ($key as $i=>$k) {
if (is_object($value) && isset($value->{$k})) {
$value = $value->{$k};
} elseif (is_array($value) && isset($value[$k])) {
$value = $value[$k];
} elseif ($i == count($key) - 1) {
$value = null;
}
}
return $value;
}
Usage:
$o = (object)[
"extra_info" => (object)[
"status" => "AlreadyVerified"
]
];
echo deepFind($o, 'extra_info->status');
Online demo
This is one way to do it, albeit potentially insecure depending on where $key comes from:
<?php
$object = new stdClass();
$object->extra_info = new stdClass();
$object->extra_info->status = 'AlreadyVerified';
$key = 'extra_info->status';
eval( 'echo $object->'.$key.';' );
Output:
AlreadyVerified
Additionally, if you wanted to parse $key then you could use a recursive function to access the nested value.
I am trying to handle a situation with a nested multiple array that is received in PHP by $_POST from Javascript-Jquery (as Object not as Json)
. The nested Object looks like this:
{
"Videotheck":{
{
"Category":"Comedy",
"Title_Liste":[
{
"Title":"Millers",
"Year":"2014"
},
{
"Title":"Yogi",
"Year":"2012"
}
]
},
{
"Category":"Action",
"Title_Liste":[
{
"Title":"Rodulf",
"Year":"2014"
},
{
"Title":"Matrix",
"Year":"2000"
}
]
}
}
}
And now the information in this Object need to be splited. For example the title list of each category should be stored in a var
$comedy_title_liste = [];
$action_title_liste = [];
I tryed this:
if($_POST){
$arr1 = $_POST['Videotheck'];
foreach($arr1 as $vtk){
foreach($vtk as $data => $v){
foreach($v as $key => $value){
foreach($value as $k => $info){
echo $k.' '. $info;
}
}
}
}
}
Like this I can get only all title list from all categories, but is necessary to get for each category the list of titles separeted. I don't know really how to handle the situation.
Well this is what I have. I guest that there is something not correct.
Not 100% exact but you can give a try :
$result = array();
$parent = $_POST['Videotheck'];
foreach($parent as $key=> $child) {
$result[$child['Category']."_title_liste"] = array();
foreach($child['Title_Liste'] as $cKey => $val) {
$result[$child['Category']."_title_liste"][] = $val['Title'];
}
}
[{"name":"se","value":"test1"},{"name":"model","value":"test2"},{"name":"filter_preference","value":"test3"},{"name":"seved","value":"test4"}]
I have json, and I would like to parse it, and to get for "segment" => "test1"
and so on.
i have done this
$json2= json_encode($loadFilter);
$json2 = json_decode($json2, true);
foreach ($json2->$key as $value)
{
echo $key ."=>".$value;
}
always getting Invalid argument supplied for foreach() !!!
I am doing it WP ajax callback.
Your foreach syntax is wrong to access the $key.
foreach ($json2 as $key => $value) {
echo $key ."=>".$value;
}
Edit from your comments:
You didn't give the "real" format in your question, your array is contained in 'filter_preference', so you have to iterate over $json2['filter_preference'].
foreach ($json2['filter_preference'] as $key => $value) {
echo $key ."=>".$value;
}
you need to map key value for sub array.
try this:
foreach ($json2 as $key=>$value)
{
echo $key ."=>".$value;
}
One odd suggestion here:
If you want to use array for this then you can convert object to array using following code:
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
$array_new = objectToArray($json2);
http://wonderphp.wordpress.com/2014/03/20/convert-object-to-array-and-vice-versa/
How do i perform foreach on a object . I wish to format the result that i get in my ci query
foreach ($CIResult as $key => $value) {
$CIResult -> $key = MyCustomFunction($value);
}
EDIT
I want CIResult to stay as a object only
foreach ($CIResult as $key => &$value) {
$value = MyCustomFunction($value);
}
It's important to note that this will only work on public properties of your object.
You can always cast an object to an array.
foreach ($CIResult as &$object) //by reference
{
$object->property = $new_value;
}
Is this what you want ?
foreach ($CIResult as $ciObj) {
// Access object properties like
$ciObj->property_name = format_name($ciObj->property_name);
}
Can you please, be more explicit on what you want to format ?
foreach((array)$CIResult as $key => $value)
$CIResult->$key = MyCustomFunction($value);