PHP Combining arrays with std class - php

This is what I want but cant figure out how to.
$a is this array
PHP Code:
Array
(
[0] => stdClass Object
(
[id] => i1
[cat] => Test1
)
[1] => stdClass Object
(
[id] => i2
[cat] => Test2
)
[2] => stdClass Object
(
[id] => i3
[cat] => Test3
)
[3] => stdClass Object
(
[id] => i4
[cat] => Test4
)
}
This is the array and it has those std classes associated with it. What I am trying to do is to combine all the "cat" names into one array variable.
I want to make $categories an array with all these "cat" as the array values.
How can I do that ?

array_map($a, function(stdClass $o) { return $o->cat; });

A simple way is just to loop over the array, grabbing the values that you want. There are other, fancier ways of doing the same but I like to keep it simple.
$categories = array();
foreach ($a as $obj) {
$categories[] = $obj->cat;
}
Of course, if not all of the array items are that object then it might be worthwhile to check that the cat property exists (and that $obj is a stdClass!).

Simply loop through and create a new array...
<?php
$newArray = array();
foreach($a as $cat) {
$newArray[$cat->id] = $cat->cat;
}
var_dump($newArray);

Related

Problems changing values in an array/object nested combination array

I don't know what to do to get this done what would like to do. I tried multiple approaches, e.g. I used array_map, array_walk, nested foreach loops with get_object_vars and I worked with json_decode/encode and so on. I always come a little bit further but never reach my goal and I would like to get some guidance from you
Basically when you see the array below, how would you proceed when you want to change some value in the path array for multiple values in the array itself?
My questions:
1) Is it right that I must convert both nested objects to an array first or is this not nesessary to do this? I mean I always get some type conversion error which tells me that I either have everything as an object or array. Is this right?
2) If this mistery is solved, which php array function is the appropriate one to change values in an array(/object)? As I have written above, I tried so many and I don't see the trees in the woods anymore. Which one do you suggest to me to use in a foreach loop?
Array
(
[0] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Bob
[1] => pictures
[2] => food
)
)
)
[1] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Alice
[1] => pictures
[2] => vacations
[3] => rome
)
)
)
)
I would suggest that,
you create an array with keys as new path and value as old path (
path to be replaced).
Loop you path array and check if it is available in above defined array.
If available replace it with key of above defined array.
For example
// array defined as point 1
$change_path_array= array('pics'=>'pictures','meal'=>'food');
// $array is your array.
foreach ($array as $value) {
// loop you path array
for($i=0;$i<count($value->doc->path);$i++){
// check if the value is in defined array
if(in_array($value->doc->path[$i],$change_path_array)){
// get the key and replace it.
$value->doc->path[$i] = array_search($value->doc->path[$i], $change_path_array);
}
}
}
Out Put: picture is replaced with pics and food with meal
Array
(
[0] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Bob
[1] => pics
[2] => meal
)
)
)
[1] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Alice
[1] => pics
[2] => vacations
[3] => rome
)
)
)
)
You can modify the code to check casesensitive.
Example of changing all pictures to photos:
$doc1 = new \stdClass;
$doc1->doc = new \stdClass;
$doc1->doc->path = array('Bob', 'pictures', 'food');
$doc2 = new \stdClass;
$doc2->doc = new \stdClass;
$doc2->doc->path = array('Alice', 'pictures', 'vacations', 'rome');
$documents = array($doc1, $doc2);
/* change all 'pictures' to 'photos' */
foreach ($documents as &$doc) {
foreach ($doc->doc->path as &$element) {
if ($element == 'pictures') {
$element = 'photos';
}
unset($element);
}
unset($doc);
}
print_r($documents);
You can do it like this:
for($i = 0; $i < count($arr); $i++){
$path_array = $arr[$i]->doc->path;
// do your modifications for [i]th path element
// in your case replace all 'Bob's with 'Joe's
$path_array = array_map(function($paths){
if($paths == 'Bob') return 'Joe';
return $paths;
}, $paths_array);
$arr[$i]->doc->path = $path_array;
}

Extracting a property from an array of an array of objects

I've got an object, containing an array of objects, containing an array of values:
stdClass Object (
[devices] => Array (
[0] => stdClass Object (
[location] => 1
[delegate] =>
[type] => 1
[id] => 1234
[IP] => 1.2.3.4
[name] => host1
[owner] => user6
[security] => 15
)
[1] => stdClass Object (
[location] => 2
[delegate] =>
[type] => 1
[id] => 4321
[IP] => 4.3.2.1
[name] => host2
[owner] => user9
[security] => 15
)
)
)
I want to extract just the id and name into an array in the form of:
$devices['id'] = $name;
I considered using the array_map() function, but couldn't work out how to use it... Any ideas?
This will generate you a new array like I think you want
I know you says that delegate is an object but the print does not show it that way
$new = array();
foreach($obj->devices as $device) {
$new[][$device->id] = $device->name;
}
Would something like this not work? Untested but it cycles through the object structure to extract what I think you need.
$devices = myfunction($my_object);
function myfunction($ob){
$devices = array();
if(isset($ob->devices)){
foreach($ob->devices as $d){
if(isset($d->delegate->name && isset($d->delegate->id))){
$devices[$d->delegate->id] = $d->delegate->name;
}
}
}
return($devices);
}
Im usually using this function to generate all child and parent array stdclass / object, but still make key same :
function GenNewArr($arr=array()){
$newarr = array();
foreach($arr as $a=>$b){
$newarr[$a] = is_object($b) || is_array($b) ? GenNewArr($b) : $b ;
}
return $newarr;
}

PHP - Get All values from object without knowing properties

I'm having an issue with displaying object properties.
normally you would call them using :
$obj["name"]
but what if you did not know the properties e.g "name"
for an array , you can simply call $arr[0] , $arr[1] etc...
But if i have this object (print_r):
stdClass Object ( [id] => 1 [Name] => george [Number] => 437439742 [Email] => hds#gmail.com)
stdClass Object ( [id] => 2 [Name] => tom [Number] => 4343554643 [Email] => fdhk#gmail.com)
how can i use a foreach to display all the values e.g : 1 , george , 437...
-Without knowing the name of the properties -> NOT $o["id"];
foreach($object as $o)
{
echo $o[i]; // doesn't work on objects
}
I tried converting it to arrays , but it will be an array of the objects so i can;t get the inside info.
//$array = array ($object);
You have a couple of options. One is the get_object_vars() function, and another is to cast the object to an array.
foreach (get_object_vars($object) as $var => $val) {
// ...
}
or
foreach ((array) $object as $var => $val) {
// ...
}
You can use:
$array = get_object_vars($obj);

dynamically create arrays from multidimensional array

So if having a multidimensional array like:
Got it from here (as a demo): PHP. Loop through an array and get items with attributes in common
$data
Array
(
[0] => stdClass Object
(
[term_id] => 3
[name] => Comercial
)
[1] => stdClass Object
(
[term_id] => 4
[name] => Escolar
)
[2] => stdClass Object
(
[term_id] => 5
[name] => Kinder
)
[3] => stdClass Object
(
[term_id] => 6
[name] => Primaria
)
[4] => stdClass Object
(
[term_id] => 7
[name] => Secundaria
)
[5] => stdClass Object
(
[term_id] => 1
[name] => Uncategorized
)
)
Having 0,1,2,3,4,5 stdClass Objects, how can I create individual arrays for each std Object dynamically.
By that I mean that the function should be able to create $varX array, where X is the array number of the stdObject, automatically...
$var0 = $data[0];
$var1 = $data[1];
and so on, determined by $data first level count of arrays.
Edit:
I got carried away and forgot to mention the most important question:
Having $var0, $var1... is very important because for a later use of all or each one individually.
So
Needs to create X variables according to the count of first level of the multidimensional array
each $varX needs to be accessible in common with the rest of $varX or individually.
$count = count($data); //6
foreach ($data as $key => $value)
{
$var.$key = $value;
}
Ok, that function works partially because from there I don't know how to make it automatically add $val1,$val2... to (ex:) array_intersect($val1,$val2,$val3...
The easiest way would be to use extract.
extract($data, EXTR_PREFIX_ALL, 'var');
With that said, it will add an underscore (_) after the prefix (e.g. var_0).
Update:
Regarding your edit, you could simply call array_intersect using call_user_func_array. There's no need for variables.
call_user_func_array('array_intersect', $data);
foreach ($data as $key => $obj)
{
$key = 'var'.$key;
$$key = $obj;
}
You can just cast each object to an array.
foreach ($data AS $key => $datum)
{
$data[$key] = (array) $datum;
}
For your update:
foreach ($data AS $key => $datum)
{
$newkey = 'var' . $key; // we want the variable to be called "var" plus the number
$$newkey = (array) $datum; // Make it an array
$data[$key] = $$newkey; // And update the $data array to contain the array
}
You now have $var0, $var1, etc and can also access them as a collection in $data, and they're in both as an array.

Multi dimensional array, with an object for good measure - iteration?

This one is starting to get on my nerves. Still fairly new to arrays and objects.
I need to be able to pull out [id] in the numbered array, plus get access to the lonely snippet_count at the end.
I can do it if there is no top level container array using a foreach $a as $k => $v., (from an earlier SO question) but am struggling a level deeper. Thanks.
Array
(
[snippets] => Array
(
[0] => stdClass Object
(
[id] => 123456789
)
[1] => stdClass Object
(
[id] => 123456789
)
[2] => stdClass Object
(
[id] => 123456789
)
//and so on
)
[snippet_count] => 500
)
You can iterate over just the snippets array to get the IDs
$ids = array();
foreach ($array['snippets'] as $snippet) {
$ids[] = $snippet->id;
}
$count = $array['snippet_count'];
Is this what you're looking for?

Categories