convert array of object to associative array - php

I need to convert below array:-
Array
(
[0] => stdClass Object
(
[id] =>
[risk_reference] =>
[risk_version] =>
[bsi] => 10.00
)
)
to below array:-
Array
(
[id] =>
[risk_reference] =>
[risk_version] =>
[bsi] => 10.00
)
I tried to do it by typecasting. But It didn't give me the output.
I also checked this link
For Above $result = (array)($array[0]) works fine for me.
But if I have the below then what will I do?
Array
(
[0] => stdClass Object
(
[id] =>
[risk_reference] =>
[risk_version] =>
[bsi] => 10.00
)
[1] => stdClass Object
(
[id] =>
[risk_reference] =>
[risk_version] =>
[bsi] => 20.00
)
)

Try this
$array = (array)($array[0]);

try this
$yourArray = array();
$i=0;
foreach ($yourObject as $key => $value) {
$yourArray[$i]['id'] = $value->id;
$yourArray[$i]['risk_reference'] = $value->risk_reference;
$yourArray[$i]['risk_version'] = $value->risk_version;
$yourArray[$i]['bsi'] = $value->bsi;
$i+=1;
}
print_r($yourArray);

http://php.net/get_object_vars
Gets the accessible non-static properties of the given object according to scope.
Returns an associative array of defined object accessible non-static properties for the specified object in scope. If a property has not been assigned a value, it will be returned with a NULL value.

Related

Parse JSON from file using PHP from objects/arrays

I get the following output using print_r in php of my decoded JSON:
stdClass Object
(
[assignments] => Array
(
[0] => stdClass Object
(
[assignmentid] => 1
[grades] => Array
(
[0] => stdClass Object
(
[id] => 1
[userid] => 3
[attemptnumber] => 0
[timecreated] => 1484244192
[timemodified] => 1484244203
[grader] => 2
[grade] => 85.00000
)
)
)
)
[warnings] => Array
(
)
)
I want to get the value for [grade] => 85.00000 and store it in a variable. How would I go about doing this?
What about:
$var = $obj->assignments[0]->grades[0]->grade;
Use true as second parameter of json_decode() to decode it to array and then you have to loop over your result.
$data = json_decode($json, true);
foreach ($data['assignments'] as $row) {
foreach ($row['grades'] as $grade) {
echo $grade['grade'];
}
}

PHP - Merge 2 arrays of object using a key/id

I want to merge the 2 arrays of objects based on the 'id' field of Array1 and the 'itemVendorCode' of Array2. I also wanted to remove from the resulting arrays of object anything that didn't match.
Array1:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
)
[1] => stdClass Object
(
[id] => 89-575-2354
[qty] => 24
[price] => 230.35
)
[2] => stdClass Object
(
[id] => 89-605-1250
[qty] => 2
[price] => 230.35
)
)
Array2:
Array
(
[0] => Item Object
(
[internalId] => 14062
[itemVendorCode] => 89-605-1250
)
[1] => Item Object
(
[internalId] => 33806
[itemVendorCode] => 89-575-2354
)
[2] => Item Object
(
[internalId] => 64126
[itemVendorCode] => 26-295-1006
)
)
I was able to solve this by this code:
$indexed = array();
foreach($itemsArray as $value) {
$indexed[$value->itemVendorCode] = $value;
}
$results = array();
foreach($vendorItems as $obj) {
$value = $indexed[$obj->id];
if (isset($value)) {
foreach($value as $name => $val) {
$obj->$name = $val;
array_push($results, $obj);
}
}
}
print_r($results);
credits to the original poster. I just modified it a bit,
I was able to get the result like this:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
[internalId] => 2035
[itemVendorCode] => 10-423-1176
)
[1] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
[internalId] => 2035
[itemVendorCode] => 10-423-1176
)
[2] => stdClass Object
(
[id] => 14-102-1010
[qty] => 16
[price] => 3.2
[internalId] => 57033
[itemVendorCode] => 14-102-1010
)
)
I think you will have to use array_map function which provides you a callback function to execute on array(s).
In the callback function:
- declare your array1
- foreach the second array
- set an if statement to check that the current iteration with the id value matches the itemVendorCode of the array2 and return it
something like this:
// You have to specify to PHP to use a local copy of your $array2 to works with it into your callback
$cb = function ($obj1) use ($array2)
{
// you foreach this array
foreach ($array2 as $obj2) {
// if the value of id matches itemVendorCode
if ($obj1->id === $obj2->itemVendorCode) {
// you return the id
return $obj->id;
}
}
};
// this function will fill a new array with all returned data
$mergedArray = array_map($cb, $array1);
This code is a sample but doesn't provide you, your needled solution, try to update it to do what you exactly want ;)

Merge 2 arrays of objects in PHP [duplicate]

This question already has answers here:
Merging and group two arrays containing objects based on one identifying column value
(4 answers)
Closed last month.
How do you merge array1 and 2?
array1
Array
(
[0] => stdClass Object
(
[name] => bob
[id] => 84569354306
[contacts] => Array
(
[0] => none
)
)
[1] => stdClass Object
(
[name] => jill
[id] => 456745742
[contacts] => Array
(
[0] => none
)
)
)
array2
Array
(
[0] => stdClass Object
(
[name] => bob
[id] => 84569354306
[pid] => 1
[lang] => eng;
[location] =>
)
[1] => stdClass Object
(
[name] => jill
[id] => 456745742
[pid] => 2
[lang] => eng;
[location] =>
)
)
Result array:
Array
(
[0] => stdClass Object
(
[name] => bob
[id] => 84569354306
[pid] => 1
[lang] => eng;
[location] =>
[contacts] => Array
(
[0] => none
)
)
[1] => stdClass Object
(
[name] => jill
[id] => 456745742
[pid] => 2
[lang] => eng;
[location] =>
[contacts] => Array
(
[0] => none
)
)
)
I've tried an array_merge() which seems to add objects next to each other in the array rather than merging the objects.
I'm pretty sure this question is similar to what I need, but I'm having difficulty with the simple foreach loop.
You can cast the two objects to array and then re-cast back to an object. The general syntax is:
$merged = (object)array_merge_recursive((array)$firstObj, (array)$secondObj);
^
| note the recursive in your case
Also, if you are using objects like that maybe you should simply stick to array. It has very little to no sense to do something like that with objects
With multiple items
If you have multiple items you simply need to wrap up my script inside a loop:
function myCustomMerge($array1, $array2) {
assert('count($array1) == count($array2)');
$result = array();
foreach($array1 as $k=>$v) {
$item = array_merge_recursive((array)$array1[$k], (array)$array2[$k]);
$result[]=$item; // use (object)$item if you need objects
}
return $result;
}
Solution without casting
If you prefer not to cast back and forth between array and object you can use get_object_vars():
$obj2props = get_object_vars($obj2);
foreach ($obj2props as $prop => $value) {
$obj1->$prop = $value;
}
return $obj;
Another way of doing it:
function merge_values(){
$list = func_get_args();
while( count( $list ) > 1 ){
$array1 = array_shift( $list );
$array2 = array_shift( $list );
$merged_array = $array1;
foreach( $array2 as $key => $value ){
$merged_array[$key] = array_merge( (array)$value, (array)$merged_array[$key] );
if( is_object( $value ) || is_object( $array1[$key] ) ){
$merged_array[$key] = (object)$merged_array[$key];
}
}
array_unshift( $list, $merged_array );
}
return current( $list );
}
$merged = merge_values( $array1, $array2 );

getting property name of php object

If i have a php object:
stdClass Object
(
[userAttributes] => stdClass Object
(
[dog] => stdClass Object
(
[type] => Canine
[required] => *
[options] =>
[size] =>
)
[cat] => stdClass Object
(
[type] => Feline
[required] => *
[options] =>
[size] =>
)
)
)
without doing a foreach loop, is it possible to print the value of the children of userAttributes. I want to print "dog" and "cat".
if this was an array:
$userAttributes['dog'] = array('type'=>'Canine'.....);
i could do key($userAttributes) and get the word dog. is there a php function that does the same thing as key on objects?
You can use get_object_vars:
$properties = get_object_vars( new yourFunction() );
print_r( $properties );
Also you can try (array) $obj cast to array as:
var_dump((array) $obj);
Try below code:
print_r($yourObject->userAttributes->dog);
EDIT:
print_r(array_keys($yourObject->userAttributes)); // will print dog, cat
http://in3.php.net/array_keys

Getting an objects property with slashes in it

I'm getting a json result back from an api request to the freebase database.
This is part of the object returned called $json. A var dump of $json:
stdClass Object
(
[name] => Abomey
[/location/statistical_region/population_growth_rate] =>
[/common/topic/article] => Array
(
[0] => stdClass Object
(
[id] => /m/0jk2c
)
)
How can I subtract the /m/0jk2c part?
$json->/common/topic/article[0]->id (obviously) doesn't work.
This should do it:
$json->{"/common/topic/article"}[0]->id
This is what you should use
$class->{'/location/statistical_region/population_growth_rate'}['/common/topic/article'][0]->id
Reason your Object looks like this
$std = new stdClass();
$std->id = '/m/0jk2c' ;
$json = new stdClass();
$json->name = "Abomey" ;
$json->{'/location/statistical_region/population_growth_rate'} = array('/common/topic/article'=>array($std));
If you run
var_dump($json->{'/location/statistical_region/population_growth_rate'}['/common/topic/article'][0]->id);
Output
string '/m/0jk2c' (length=8)
Run
echo "<pre>";
print_r($json);
Output
stdClass Object
(
[name] => Abomey
[/location/statistical_region/population_growth_rate] => Array
(
[/common/topic/article] => Array
(
[0] => stdClass Object
(
[id] => /m/0jk2c
)
)
)
)

Categories