Multidimensional arrays in Ruby like PHP - php

I'm a bit fuzzy on how to work with multidimensional arrays in Ruby. How would I recreate this PHP code in Ruby?
$objs_array = array();
foreach($objs AS $obj) {
$objs_array[$obj->group_id][] = $obj;
}
}
print_r($objs_array);
The result would be:
Array
(
[123] => Array
(
[0] => Array
(
object1
)
[1] => Array
(
object2
)
)
[456] => Array
(
[0] => Array
(
object3
)
[1] => Array
(
object4
)
)
)
Thanks.

More than a multidimensional array, hash of arrays would fit better.
In php you only have the type array, but in ruby the class Hash is very useful
objs_hash = {}
objs.each do |obj|
objs_hash[obj.id] = obj
end

Thank you rhernado for sending me down the road of looking into hashes. I ended up finding a similar question that pointed out the group_by method:
Building Hash by grouping array of objects based on a property of the items - I ended up using a hash of an array of objects by using:
groups = objs.group_by { |obj| obj.group_id }

Related

multidimensional array to indexed array in php

i have this multidimensional array.
Array
(
[0] => Array
(
[car] => Toyota
)
[1] => Array
(
[car] => Ford
)
[2] => Array
(
[car] => Isuzu
)
[3] => Array
(
[car] => Chevrolet
)
)
i want to put them into indexed array like this..
Array = ("Toyota", "Ford", "Isuzu", "Chevrolet");
$result = array_map(function($item)
{ return $item['car']; }, $array);
Some functional approach. array_map
P.S. PHP has no indexed arrays
foreach($yourArray as $carArray)
{
$result[]=$carArray["car"];
}
And your understanding of indexed arrays is wrong. That example output you've shown contains all those values, not indexes, and since you didn't specify an index it will start from 0 and so on.
Option using array_map(), assuming your initial array is $arr
$new_arr = array_map(function($x){return $x['car'];}, $arr);
See demo
try using foreach and array_values, then save it into empty array. Hope it helps.

PHP, Merge keys in multidimensional array

If I have an array which looks something like this:
Array
(
[0] => Array
(
[DATA] => Array
(
VALUE1 = 1
VALUE2 = 2
)
)
[1] => Array
(
[DATA] => Array
(
VALUE3 = 3
VALUE4 = 4
)
)
)
And would like to turn it into this:
Array
(
[0] => Array
(
[DATA] => Array
(
VALUE1 = 1
VALUE2 = 2
VALUE3 = 3
VALUE4 = 4
)
)
)
I basically want to merge all the identical keys which are at the same level.
What would be the best route to accomplish this?
Could the array_merge functions be of any use?
I Hope this makes any sort of sense and thanks in advance for any help i can get.
You can use array_merge_recursive to merge all the items in your original array together. And since that function takes a variable number of arguments, making it unwieldy when this number is unknown at compile time, you can use call_user_func_array for extra convenience:
$result = call_user_func_array('array_merge_recursive', $array);
The result will have the "top level" of your input pruned off (logical, since you are merging multiple items into one) but will keep all of the remaining structure.
See it in action.

PHP Convert multidimensional array to match format of another

I have two arrays, one is generated by using explode() on a comma separated string and the other is generated from result_array() in Codeigniter.
The results when doing print_r are:
From explode():
Array
(
[0] => keyword
[1] => test
)
From database:
Array
(
[0] => Array
(
[name] => keyword
)
[1] => Array
(
[name] => test
)
)
I need them to match up so I can use array_diff(), what's the best way to get them to match? Is there something other than result_array() in CI to get a compatible array?
You could create a new array like this:
foreach($fromDatabase as $x)
{
$arr[] = $x['name'];
}
Now, you will have two one dim arrays and you can run array_dif.
$new_array = array();
foreach ($array1 as $line) {
$new_array[] = array('name' => $line);
}
print_r($new_array);
That should work for you.

array_count_values() with objects as values

I was wondering, is there something similar to array_count_values, but that works with objects ?
Let me explain:
array_count_values takes an array as argument, such as
[1]
Array (
[0] => banana
[1] => trololol
)
If i give that array to array_count_values, i will get something like:
[2]
Array (
[banana] => 1
[trololol] => 1
)
Now lets say that instead of strings, i have objects, that i want to count based on one of their properties. So i have:
[3]
Array (
[0] => stdClass Object (
[name] => banana
[description] => banana, me gusta!
)
[1] => stdClass Object (
[name] => trololol
[description] => trolololololol
)
)
And i'd want the magical-function-im-looking-for to count the number of objects with the same name property, returning the same input as [2]
Obviously i could easily do that on my own, but i was just wondering if there was a built-in function for that, since i couldnt seem to find one. Thanks, kind SOers!
No such function exists. You always need to first map the values you would like to count (and those values must be string or integer):
$map = function($v) {return $v->name;};
$count = array_count_values(array_map($map, $data));
Since PHP 7.0, you can use array_column for this.
$counts = array_count_values(array_column($array_of_objects, 'name'));
When this question was originally asked and answered array_column didn't exist yet. It was introduced in PHP 5.5, but it couldn't handle arrays of objects until 7.0.
Check out the Reflection classes to easily fetch information about your objects dynamically.

Compare array attributes

I would like to compare two array items with php, I think I should use array_intersect_key but I don't know how I can do that.
Array 1
[1] => obj Object
(
[idobj:protected] => 2
)
[2] => obj Object
(
[idobj:protected] => 1
)
Array 2
[1] => obj Object
(
[idobj:protected] => 1
)
No, you don't need to use array_intersect_key() if you need only to compare array elements.
It simple like this (for two-dimensional arrays):
if( $array1[0] == $array2[0] ) {
echo 'Array items are equal';
} else {
echo 'Array items are not equal';
}
If you have multi-dimensional array you may need add some extra indexes.
PHP manual has a very good information regarding arrays, check it out.
Are you actually looking for array_intersect()?
$objectsInArray1ThatArePresentInArray2 = array_intersect($array1, $array2);

Categories