I have the following code but I am wondering how I can make it more efficient.
if ($genres){
$arr = array();
foreach ($genres as $i) {
$arr[] = $i->name;
}
$genres_arr = $arr;
}
if ($themes){
$arr = array();
foreach ($themes as $i) {
$arr[] = $i->name;
}
$themes_arr = $arr;
}
var_dump($genres_arr);
var_dump($themes_arr);
I've tried putting them into an if statement but because they both always exists only the first one runs. I want to check to see if both exist and always run them both through a foreach loop. If only one exists I want only the one to run.
These are the array structures.
["genres"]=>
array(1) {
[0]=>
object(stdClass)#1579 (2) {
["id"]=>
int(25)
["name"]=>
string(26) "Hack and slash/Beat 'em up"
}
}
["themes"]=>
array(3) {
[0]=>
object(stdClass)#1576 (2) {
["id"]=>
int(1)
["name"]=>
string(6) "Action"
}
}
I want to have them as flattered as at the moment they are inside objects. I am then going to implode them into a list for WordPress use.
This code works but its repetitive and some help would be great!
I think you can use array column because it can read values from "A multi-dimensional array or an array of objects from which to pull a column of values from" like this:
if ($genres) {
$genres_arr = array_column($genres, 'name');
}
if ($themes) {
$themes_arr = array_column($themes, 'name');
}
var_dump($genres_arr);
var_dump($themes_arr);
In this way the easiest simplification would be to introduce a new function, which builds the array.
function getNames($arr) {
if (!is_array($arra)) return false;
return array_map(function($item) {
return $item->name;
}, $arr);
}
$themes_arr = getNames($themes);
$genre_arr = getNames($genres);
This is how I would combine them
$sets = [];
if ($genres){
$sets['genres'] = $genres;
}
if ($themes){
$sets['themes'] = $themes;
}
$arr = array();
foreach( $sets as $type => $data ){
foreach ($genres as $i) {
$arr[$type][] = $i->name;
}
}
claudio's answer is perfect for this situation, but in the more general case you can also define a mapping function, which you then use with array_map for both sets of objects, e.g.
$mapper = function ($item) { return $item->name; };
$genres_arr = array_map($mapper, $genres);
$themes_arr = array_map($mapper, $themes);
This has the advantage of being able to run more complex logic (using a getter function instead of direct property access, etc), if you need it in future.
Ideally, both objects would implement a common interface, so that it was clear exactly what kinds of objects the mapping function was designed for.
Related
I may not word this issue properly, so here's what am trying to achieve.
array {
[0]=> {
["Abilities"]=> { ["Numerical"]=> 3 }
}
[1]=> {
["Abilities"]=> { ["Verbal"]=> 1 }
}
[2]=> {
["Domain"]=> { ["Programming"]=> 0 }
}
}
to
array {
[0]=> {
["Abilities"]=> { ["Numerical"]=> 3 ["Verbal"]=> 1 }
}
[1]=> {
["Domain"]=> { ["Programming"]=> 0 }
}
}
I get this array from an external source so I need optimized this way to use it.
The array you're getting from an external source is like a set of separate branches you need to merge into a single tree. You can use a recursive function to create the "optimized" structure you're going for. A recursive approach should work regardless of the depth of each branch.
function merge_branches(array $branches): array
{
$merge = function ($node, &$tree) use (&$merge) {
if (is_array($value = reset($node))) {
$merge($value, $tree[key($node)]); // merge branch node recursively
} else {
$tree[key($node)] = $value; // set leaf node to value
}
};
$tree = [];
foreach ($branches as $branch) {
$merge($branch, $tree);
}
return $tree;
}
$optimized = merge_branches($external);
I have a lot of functions stored in an associative array like this :
$arr['my-title'] = function(){process(146,'My Title');};
$arr['un-cafe-chaud'] = function(){process(857,'Un café chaud');};
$arr['vpn'] = function(){process(932,'VPN');};
$arr['another-example'] = function(){process(464,'Another example');};
Currently I have to encode manually each key.
As the key name is function of the Title, I'd like to automate it.
function assign_keys($title,$id){
$u=str_replace(array(' ','é'),array('-','e'),strtolower($title));
$arr[$u] = function(){process($id,$title);};
}
But it doesn't work, as process function can't get $id and $title value.
Any help on how I could handle this would be highly appreciated ! Thank you.
First of all, you should pass $arr as argument to the function in order to be able to mutate it. Second, you should use use to make those two variables available in the anonymous function, like this:
function assign_keys($title,$id, &$arr){
$u=str_replace(array(' ','é'),array('-','e'),strtolower($title));
$arr[$u] = function() use ($id, $title){process($id,$title);};
}
Then use it like this:
$arr = [];
assign_keys('Some title', 123, $arr);
var_dump($arr);
This should print:
array(1) {
["some-title"]=>
object(Closure)#1 (1) {
["static"]=>
array(2) {
["id"]=>
int(123)
["title"]=>
string(10) "Some title"
}
}
}
You probably want a reference & to get the array outside of the function and use to get the variables into the closure:
function assign_keys($title, $id, &$arr){
$u = str_replace(array(' ','é'), array('-','e'), strtolower($title));
$arr[$u] = function() use($title, $id) { process($id, $title); };
}
assign_keys('My Title', 146, $arr);
As title, I did it like below:
$array=array(0,1,2,3);
$result=array();
function makeArray($array,$result,$value){
$str='$result';
for ($i=0;$i<count($array);$i++){
$str.='['.$i.']';
}
$str.='="'.$value.'";';
eval($str);
return $result;
}
It can realize result when param $result is an empty array,but It report an error when $result is an array.
Error like :
Cannot use a scalar value as an array.
Anyways can realize it?
Thanks first!
Use pass by reference, not eval:
function makeArray($indexes, &$result, $value) {
$here =& $result;
foreach ($indexes as $i) {
if (!(isset($here[$i]) && is_array($here[$i]))) {
$here[$i] = array();
}
$here =& $here[$i];
}
$here = $value;
}
$array=array(0,1,2,3);
$result=array();
makeArray($array, $result, 3);
var_dump($result);
Output:
array(1) {
[0]=>
array(1) {
[1]=>
array(1) {
[2]=>
array(1) {
[3]=>
int(3)
}
}
}
}
Putting & before a function parameter means it will be passed by reference, so modifications to the variable inside the function will affect the original variable that was passed. And using =& in an assignment assigns a reference, so the target variable is an alias for the source.
I'm looking for a sort of reversed func_get_args(). I would like to find out how the parameters were named when function was defined. The reason for this is I don't want to repeat myself when using setting variables passed as arguments through a method:
public function myFunction($paramJohn, $paramJoe, MyObject $paramMyObject)
{
$this->paramJohn = $paramJohn;
$this->paramJoe = $paramJoe;
$this->paramMyObject = $paramMyObject;
}
Ideally I could do something like:
foreach (func_get_params() as $param)
$this->${$param} = ${$param};
}
Is this an overkill, is it a plain stupid idea, or is there a much better way to make this happen?
You could use Reflection:
$ref = new ReflectionFunction('myFunction');
foreach( $ref->getParameters() as $param) {
echo $param->name;
}
Since you're using this in a class, you can use ReflectionMethod instead of ReflectionFunction:
$ref = new ReflectionMethod('ClassName', 'myFunction');
Here is a working example:
class ClassName {
public function myFunction($paramJohn, $paramJoe, $paramMyObject)
{
$ref = new ReflectionMethod($this, 'myFunction');
foreach( $ref->getParameters() as $param) {
$name = $param->name;
$this->$name = $$name;
}
}
}
$o = new ClassName;
$o->myFunction('John', 'Joe', new stdClass);
var_dump( $o);
Where the above var_dump() prints:
object(ClassName)#1 (3) {
["paramJohn"]=>
string(4) "John"
["paramJoe"]=>
string(3) "Joe"
["paramMyObject"]=>
object(stdClass)#2 (0) {
}
}
Code snippet that creates an array containing parameter names as keys and parameter values as corresponding values:
$ref = new ReflectionFunction(__FUNCTION__);
$functionParameters = [];
foreach($ref->getParameters() as $key => $currentParameter) {
$functionParameters[$currentParameter->getName()] = func_get_arg($key);
}
While it's not impossible to do it, it's usually better to use another method. Here is a link to a similar question on SO :
How to get a variable name as a string in PHP?
What you could do is pass all your parameters inside of an object, instead of passing them one by one. I'm assuming you are doing this in relation to databases, you might want to read about ORMs.
get_defined_vars will give you the parameter names and their values, so you can do
$params = get_defined_vars();
foreach ($params as $var=>$val) {
$this->${var} = $val;
}
This question already has answers here:
Convert a PHP object to an associative array
(33 answers)
Closed 6 months ago.
I'm using amazon product advertising api. Values are returned as a multidimensional objects.
It looks like this:
object(AmazonProduct_Result)#222 (5) {
["_code":protected]=>
int(200)
["_data":protected]=>
string(16538)
array(2) {
["IsValid"]=>
string(4) "True"
["Items"]=>
array(1) {
[0]=>
object(AmazonProduct_Item)#19 (1) {
["_values":protected]=>
array(11) {
["ASIN"]=>
string(10) "B005HNF01O"
["ParentASIN"]=>
string(10) "B008RKEIZ8"
["DetailPageURL"]=>
string(120) "http://www.amazon.com/Case-Logic-TBC-302-FFP-Compact/dp/B005HNF01O?SubscriptionId=AKIAJNFRQCIJLTY6LDTA&tag=*********-20"
["ItemLinks"]=>
array(7) {
[0]=>
object(AmazonProduct_ItemLink)#18 (1) {
["_values":protected]=>
array(2) {
["Description"]=>
string(17) "Technical Details"
["URL"]=>
string(217) "http://www.amazon.com/Case-Logic-TBC-302-FFP-Compact/dp/tech-data/B005HNF01O%3FSubscriptionId%3DAKIAJNFRQCIJLTY6LDTA%26tag%*******-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB005HNF01O"
}
}
[1]=>
object(AmazonProduct_ItemLink)#17 (1) {
["_values":protected]=>
array(2) {
I mean it also has array inside objects. I would like to convert all of them into a multidimensional array.
I know this is old but you could try the following piece of code:
$array = json_decode(json_encode($object), true);
where $object is the response of the API.
You can use recursive function like below:
function object_to_array($obj, &$arr)
{
if (!is_object($obj) && !is_array($obj))
{
$arr = $obj;
return $arr;
}
foreach ($obj as $key => $value)
{
if (!empty($value))
{
$arr[$key] = array();
objToArray($value, $arr[$key]);
}
else {$arr[$key] = $value;}
}
return $arr;
}
function convertObjectToArray($data) {
if (is_object($data)) {
$data = get_object_vars($data);
}
if (is_array($data)) {
return array_map(__FUNCTION__, $data);
}
return $data;
}
Credit to Kevin Op den Kamp.
I wrote a function that does the job, and also converts all json strings to arrays too. This works pretty fine for me.
function is_json($string) {
// php 5.3 or newer needed;
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
function objectToArray($objectOrArray) {
// if is_json -> decode :
if (is_string($objectOrArray) && is_json($objectOrArray)) $objectOrArray = json_decode($objectOrArray);
// if object -> convert to array :
if (is_object($objectOrArray)) $objectOrArray = (array) $objectOrArray;
// if not array -> just return it (probably string or number) :
if (!is_array($objectOrArray)) return $objectOrArray;
// if empty array -> return [] :
if (count($objectOrArray) == 0) return [];
// repeat tasks for each item :
$output = [];
foreach ($objectOrArray as $key => $o_a) {
$output[$key] = objectToArray($o_a);
}
return $output;
}
This is an old question, but I recently ran into this and came up with my own solution.
array_walk_recursive($array, function(&$item){
if(is_object($item)) $item = (array)$item;
});
Now if $array is an object itself you can just cast it to an array before putting it in array_walk_recursive:
$array = (array)$object;
array_walk_recursive($array, function(&$item){
if(is_object($item)) $item = (array)$item;
});
And the mini-example:
array_walk_recursive($array,function(&$item){if(is_object($item))$item=(array)$item;});
In my case I had an array of stdClass objects from a 3rd party source that had a field/property whose value I needed to use as a reference to find its containing stdClass so I could access other data in that element. Basically comparing nested keys in 2 data sets.
I have to do this many times, so I didn't want to foreach over it for each item I need to find. The solution to that issue is usually array_column, but that doesn't work on objects. So I did the above first.
Just in case you came here as I did and didn't find the right answer for your situation, this modified version of one of the previous answers is what ended up working for me:
protected function objToArray($obj)
{
// Not an object or array
if (!is_object($obj) && !is_array($obj)) {
return $obj;
}
// Parse array
foreach ($obj as $key => $value) {
$arr[$key] = $this->objToArray($value);
}
// Return parsed array
return $arr;
}
The original value is a JSON string. The method call looks like this:
$array = $this->objToArray(json_decode($json, true));