Best method to get single value array from multi value array - php

Have array like this:
Array
(
[0] => Array
(
[Slot_id] => 7048,
[name] => value
)
[1] => Array
(
[Slot_id] => 7049,
[name] => value
)
)
I want to get the below array form
Slot_id => Array
(
[0] => 7048,
[1] => 7049
)
currently i am using foreach function, any other best method?

If you are using PHP >= 5.5 then array_column is the solution:
$result = array_column($input, 'Slot_id');
For earlier versions, either manually foreach or alternatively:
with array_map:
// assumes PHP 5.3 for lambda function, for earlier PHP just do foreach
$result = array_map(function($row) { return $row['Slot_id']; }, $input);
with array_walk:
// assumes PHP 5.4 for short array syntax, for 5.3 use array() instead of []
$result = [];
array_walk($input, function($row) use (&$result) { $result[] = $row['Slot_id']; });

Use array_column function:
https://php.net/manual/fr/function.array-column.php
$subArray = array_column ($your_array, 'Slot_id');

Related

Calculate items of multidimensional array

I want to merge some multidimension arrays and calculate the values of their items. For example :
Array
(
[0] => Array
(
[0] => Array
(
[nr_colete] => 6
)
)
[1] => Array
(
[0] => Array
(
[nr_colete] => 22
)
)
)
I want to get a solution to combine them and get a result such as
Array
(
[0] => Array
(
[nr_colete] => 6 + 22
)
)
Is there a native php function to help me get this result ? I try to found one.
I can't think of one single php native function to do this, but you can do it very simply using a foreach loop.
$sum = 0;
foreach($array AS $k => $value) {
$sum += $value[0]['nr_colete'];
}
Here is the code in action
No native function which will do that directly.But you can use array_column() and array_sum() two native function to get your desired result.
Check below code:-
$final_array[0]['nr_colete'] = array_sum(array_column(array_column($array,0),'nr_colete'));
print_r($final_array);
Output:- https://eval.in/873338
Reference:-
array_column()
array_sum()

How to extract multidimensional associative array to simple numeric array

Here is a code sample
Array
(
[0] => Array
(
[ID] => 1197
)
[1] => Array
(
[ID] => 1078
)
)
I want it to convert into simple index array as:
Array( 1197, 1078 )
I know it can be done by iterating each index and assigning into a temp array. I want a one liner syntax like array_filter do in many cases. Is there any built-in function in PHP which do my task in one line, any mix of statement in one line. I don't want to use it in loops.
If you are using PHP > 5.5.0, you can use array_column:
$ids = array_column($array, 'ID');
On the linked page, you'll find a substitute for older versions:
if(!function_exists("array_column"))
{
function array_column($array,$column_name)
{
return array_map(function($element) use($column_name){return $element[$column_name];}, $array);
}
}

flatten multidimensional array

I need some help formatting an array i get from an api, the current format is hard for me to work with so i want to change it for something more workable.
I have the following array:
[attributes] => Array
(
[0] => Array
(
[attribute] => Healing
[modifier] => 179
)
[1] => Array
(
[attribute] => Toughness
[modifier] => 128
)
[2] => Array
(
[attribute] => ConditionDamage
[modifier] => 128
)
and i want to turn it into this:
[attributes] => Array
(
[Healing] => 179
[Toughness] => 128
[ConditionDamage] => 128
)
any help would be appreciated.
If you're using PHP >= 5.5
$array['attributes'] = array_column(
$array['attributes'],
'attribute',
'modifier'
);
else
$array['attributes'] = array_walk(
$array['attributes'],
function (&$value) {
$value[$value['attribute']] = $value['modifier'];
unset($value['attribute'], $value['modifier']);
}
);
Using PHP >= 5.5, you can take advantage of array_column(), in conjunction with array_combine().
$new_arr = array_combine(array_column($arr, 'attribute'), array_column($arr, 'modifier'));
See demo
Otherwise, a simple foreach will work:
foreach ($arr as $ar) {
$new_arr[$ar['attribute']] = $ar['modifier'];
}
See demo
function flattenAPIarray($APIArray)
{
$flatArray = [];
foreach($APIArray as $element)
{
$key = array_keys($element);
$flatArray[$element[$key[0]]] = $element[$key[1]];
}
return $flatArray;
}
Try this function, I wrote for you. It's not generalized in any manner, but works fine with your multidimensional associative array. The clue is to use the array_keys() function, as you don't have any index to iterate using the foreach loop.
Hope that helps! (It's my first answer - be kind :o)

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.

Select only unique array values from this array

I have the following variable $rows:
Array (
[0] => stdClass Object
(
[product_sku] => PCH20
)
[1] => stdClass Object
(
[product_sku] => PCH20
)
[2] => stdClass Object
(
[product_sku] => PCH19
)
[3] => stdClass Object
(
[product_sku] => PCH19
)
)
I need to create second array $second containing only unique values:
Array (
[0] => stdClass Object
(
[product_sku] => PCH20
)
[1] => stdClass Object
(
[product_sku] => PCH19
)
)
But when i run array_unique on $rows, i receive:
Catchable fatal error: Object of class stdClass could not be
converted to string on line 191
array_unique()
The optional second parameter sort_flags may be used to modify the sorting behavior using these values:
Sorting type flags:
SORT_REGULAR - compare items normally (don't change types)
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale.
Also note the changenotes below
5.2.10 Changed the default value of sort_flags back to SORT_STRING.
5.2.9 Added the optional sort_flags defaulting to SORT_REGULAR. Prior to 5.2.9, this function used to sort the array with SORT_STRING internally.
$values = array_unique($values, SORT_REGULAR);
$uniques = array();
foreach ($array as $obj) {
$uniques[$obj->product_sku] = $obj;
}
var_dump($uniques);
The default behavior of function array_unique() is to treat the values inside as strings first. So what's happening is that PHP is attempting to turn your objects into strings (which is throwing the error).
You can modify your function call like this:
$uniqueArray = array_unique($rows, SORT_REGULAR);
This will compare values without changing their data type.
Please check below code, I hope this will be helpful to you.
$resultArray = uniqueAssocArray($actualArray, 'product_sku');
function uniqueAssocArray($array, $uniqueKey)
{
if (!is_array($array))
{
return array();
}
$uniqueKeys = array();
foreach ($array as $key => $item)
{
$groupBy=$item[$uniqueKey];
if (isset( $uniqueKeys[$groupBy]))
{
//compare $item with $uniqueKeys[$groupBy] and decide if you
//want to use the new item
$replace= false;
}
else
{
$replace=true;
}
if ($replace)
$uniqueKeys[$groupBy] = $item;
}
return $uniqueKeys;
}

Categories