Change array key and group key with the same value - php

I have an array looks like this:
Array
(
[0] => Array
(
[variant_name] => Green
[product_id] => 2
[variant_id] => 67
[amount] => 1000
)
[1] => Array
(
[variant_name] => Red
[product_id] => 2
[variant_id] => 68
[amount] => 0
)
)
This expected to be like this:
Array (
[2] => array (
[67] => array (
[variant_id] => Green
[amount] => 1000
(
[68] => array (
[variant_id] => Red
[amount] => 0
(
)
Which is group by product_id and then split into arrays group by variant_id.
How can I do that.
Thank you so much.

foreach($values as $product)
{
$newValues[$product["product_id"]][$product["variant_id"]]=
array(
'product_name'=>$product["variant_name"],
'amount'=>$product["amount"]
);
}
Output
Array
(
[2] => Array
(
[67] => Array
(
[product_name] => Green
[amount] => 1000
)
[68] => Array
(
[product_name] => Red
[amount] => 0
)
)
)
Note You have variant_name in your original array and you are using that as variant_id in your output. You can play with indexes in this code. I just used what seemed to match.

A simple foreach loop should suffice. Of course, you need to build them inside a new array. Consider this example: (In your expected example, I think you were referring to variant_name)
$values = array( array( 'variant_name' => 'Green', 'product_id' => 2, 'variant_id' => 67, 'amount' => 1000, ), array( 'variant_name' => 'Red', 'product_id' => 2, 'variant_id' => 68, 'amount' => 0, ), );
$new_values = array();
foreach($values as $key => $value) {
$new_values[$value['product_id']][$value['variant_id']] = array(
'variant_name' => $value['variant_name'],
'amount' => $value['amount'],
);
}
echo '<pre>';
print_r($new_values);
echo '</pre>';
Sample Output

Related

Group array rows by column value and push whole rows as subarrays within the group

My input is:
$item = [
['invoice_id' => '72,', 'item' => 'SN00001'],
['invoice_id' => '73,', 'item' => 'SN00002'],
['invoice_id' => '73,', 'item' => 'SN00003'],
['invoice_id' => '73,', 'item' => 'SN00004'],
['invoice_id' => '74,', 'item' => 'SN00005'],
['invoice_id' => '74,', 'item' => 'SN00006']
];
I want to re-group it with the invoice_id like this
[0] => Array
(
[invoice_id] => 72
[group] => Array
(
[0] => Array
(
[invoice_id] => 72,
[item] => SN00001
)
)
)
[1] => Array
(
[invoice_id] => 73
[group] => Array
(
[0] => Array
(
[invoice_id] => 73,
[item] => SN00002
)
[1] => Array
(
[invoice_id] => 73,
[item] => SN00003
)
[2] => Array
(
[invoice_id] => 73,
[item] => SN00004
)
)
)
[2] => Array
(
[invoice_id] => 74
[group] => Array
(
[0] => Array
(
[invoice_id] => 74,
[item] => SN00005
)
[1] => Array
(
[invoice_id] => 74,
[item] => SN00006
)
)
)
This is what I did so far
$items = [];
foreach($item as $k => $val){
if(empty($items)){
// if first row
$items[$k]['invoice_id'] = $val['invoice_id'];
$items[$k]['group'] = [$val];
} else {
if(!empty($items)){
foreach($items as $key => $value){
if($value['invoice_id'] == $val['invoice_id']){
// if same invoice_id merge the value into the group
$items[$key]['group'] = array_merge($items[$key]['group'], [$val]);
} else {
// else create a array group
$items[$k]['invoice_id'] = $val['invoice_id'];
$items[$k]['group'] = [$val];
}
}
}
}
}
Sample: https://onecompiler.com/php/3y2hgzk79
The issue with my current codes is, it will create a duplicate item in some group. I was trying to use array_search and array_column but it didn't go as expected result so I switched to foreach instead and here I am. Any help will be much appreciated.
I have no idea why there is any need to call array_filter(), array_column(), array_search(), array_merge(), or array_unique(). Grouping the related data is matter of assigning temporary first-level keys, then unconditionally declaring or pushing the row data into the group. If you want to re-index the result array, just call array_values() after the loop finishes.
Code: (Demo)
$array = [
['invoice_id' => '72,', 'item' => 'SN00001'],
['invoice_id' => '73,', 'item' => 'SN00002'],
['invoice_id' => '73,', 'item' => 'SN00003'],
['invoice_id' => '73,', 'item' => 'SN00004'],
['invoice_id' => '74,', 'item' => 'SN00005'],
['invoice_id' => '74,', 'item' => 'SN00006']
];
$result = [];
foreach ($array as $row) {
$result[$row['invoice_id']]['invoice_id'] = $row['invoice_id'];
$result[$row['invoice_id']]['group'][] = $row;
}
var_export(array_values($result));
// output: exactly as desired in the question
Here's a fairly concise solution based on some built-in PHP array handling functions (array_map, array_filter, array_unique and array_column). It uses array_column and array_unique to get a list of distinct invoice_id values, then array_map to generate the output, filtering the input array for each entry based on whether the invoice_id values match:
$items = array_map(function ($inv_id) use ($item) {
return array('invoice_id' => $inv_id,
'group' => array_filter($item,
function ($itm) use ($inv_id) {
return $itm['invoice_id'] == $inv_id;
})
);
}, array_unique(array_column($item, 'invoice_id'))
);
Output:
Array
(
[0] => Array
(
[invoice_id] => 72,
[group] => Array
(
[0] => Array
(
[invoice_id] => 72,
[item] => SN00001
)
)
)
[1] => Array
(
[invoice_id] => 73,
[group] => Array
(
[1] => Array
(
[invoice_id] => 73,
[item] => SN00002
)
[2] => Array
(
[invoice_id] => 73,
[item] => SN00003
)
[3] => Array
(
[invoice_id] => 73,
[item] => SN00004
)
)
)
[4] => Array
(
[invoice_id] => 74,
[group] => Array
(
[4] => Array
(
[invoice_id] => 74,
[item] => SN00005
)
[5] => Array
(
[invoice_id] => 74,
[item] => SN00006
)
)
)
)
Note that internal array numbering does not start at 0; if you need that then add array_values to re-index in the appropriate places:
$items = array_values(array_map(function ($inv_id) use ($item) {
return array('invoice_id' => $inv_id,
'group' => array_values(array_filter($item,
function ($itm) use ($inv_id) {
return $itm['invoice_id'] == $inv_id;
}))
);
}, array_unique(array_column($item, 'invoice_id'))
));
Demo on 3v4l.org

Multidimensional array to single array in PHP

I am working in PHP so I have an array like this, from this array I want filter take user_id to another array like I given below.
Array
(
[0] => Array
(
[user_id] => 66
[distance] => 0
)
[1] => Array
(
[user_id] => 68
[distance] => 0
)
[2] => Array
(
[user_id] => 81
[distance] => 0
)
[3] => Array
(
[user_id] => 65
[distance] => 0.00010218008081861118
)
)
I want an array like this,
$user_id=array(66,68,81,65);
Use array_column()
Returns an array of values representing a single column from the input array.
<?php
$user_array = array(
0 => array('user_id' => 1, 'name' => 'Bob'),
1 => array('user_id' => 2, 'name' => 'John'),
2 => array('user_id' => 3, 'name' => 'Mary')
);
$users = array_column($user_array, 'user_id');
print_r($users);
Output :
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Where $array is the multidimensional array you provided above:
$data = array();
foreach ($array as $item) {
$data[] = $item['user_id'];
}
print_r($data);

Remove specific string from whole associative array items

I have an associative array. I want to remove specific string from whole array items. Here is the structure of my array:
Array
(
[50808] => Array
(
[quantity] => 2
[name] => asv (test)
)
[50809] => Array
(
[quantity] => 2
[name] => 37 (test)
)
[50810] => Array
(
[quantity] => 3
[name] => 38 (test)
)
)
Output i want:
Array
(
[50808] => Array
(
[quantity] => 2
[name] => asv
)
[50809] => Array
(
[quantity] => 2
[name] => 37
)
[50810] => Array
(
[quantity] => 3
[name] => 38
)
)
I know its very simple using loop but i want to do it without loop.
Use array_map function
<?php
$array = Array
(
'50808' => Array
(
'quantity' => 2,
'name' => 'asv (test)',
),
'50809' => Array
(
'quantity' => 2,
'name' => '37 (test)'
),
'50810' => Array
(
'quantity' => 3,
'name' => '38 (test)'
)
);
echo '<pre>';
$new_array = array_map(function($val){
$val['name'] = trim(str_replace('(test)', '', $val['name']));
return $val;
}, $array);
print_r($new_array);
Output:
Array
(
[50808] => Array
(
[quantity] => 2
[name] => asv
)
[50809] => Array
(
[quantity] => 2
[name] => 37
)
[50810] => Array
(
[quantity] => 3
[name] => 38
)
)
Another method can be array_walk function:
array_walk($array, function(&$val){
$val['name'] = trim(str_replace('(test)', '', $val['name']));
});
print_r($array); //out put: desired output

How to manipulate php arrays [duplicate]

This question already has answers here:
Group rows in an associative array of associative arrays by column value and preserve the original first level keys
(7 answers)
Closed 7 years ago.
How to manipulate php arrays. I have a $data variable below.
$data = Array
(
[0] => Array
(
[id] => 1
[capacity] => 900
[category] => users
)
[1] => Array
(
[id] => 2
[capacity] => 300
[category] => users
)
[2] => Array
(
[id] => 3
[capacity] => 900
[category] => students
)
[3] => Array
(
[id] => 4
[capacity] => 300
[category] => students
)
)
Now I want to group the data with same category like below. . I am not really familiar in php. Can somebody out there help me how to achieve this. What function should I used. Thanks
Array
(
[users] => Array
(
[0] => Array
(
[id] => 1
[capacity] => 900
[category] => users
)
[1] => Array
(
[id] => 2
[capacity] => 300
[category] => users
)
),
[students] => Array
(
[0] => Array
(
[id] => 1
[capacity] => 900
[category] => students
)
[1] => Array
(
[id] => 2
[capacity] => 300
[category] => students
)
)
)
Just iterate over the array and add it depending on the content of the category field to a new array:
$new = array();
foreach ($data as $val) {
$new[$val['category']][] = $val;
}
This does what you requested
<?php
$data = array(
0 => array (
"id" => 1,
"capacity" => 900,
"category" => "users"
),
1 => array (
"id" => 2,
"capacity" => 300,
"category" => "users"
),
2 => array (
"id" => 3,
"capacity" => 900,
"category" => "students"
),
3 => array (
"id" => 4,
"capacity" => 300,
"category" => "students"
)
);
$groups = array();
foreach ($data as $i) {
if ($i['category'] === "students") {
$groups['students'][] = $i;
}
else if ($i['category'] === "users") {
$groups['users'][] = $i;
}
}
echo "<pre>", print_r($groups), "</pre>";
Here is a working demo - http://codepad.viper-7.com/G4Br28

I've spent hours trying to get these array keys into variables but everything I try is not working

I have an array of all possible combinations of values, a bit like working out what monetary values I could make with only certain coins. Now I have an array built but much of the useful data are keys and not values.
A small snippet is below:
Each root key is an array with keys total, denomination and quantity. Each of the quantities multiplied by the denominations total the total. While I've been able to access the total easily enough I just can't get a handle on the denominations and the quantities.
It's my plan to output to separate radio buttons like so:
foreach($array as $arr)
{
echo '<input type="radio" name="name" value="'.$arr[$total].'">';
foreach($arr[denom] as $index => $d)
{
echo $d[qty][$index].' x '.$d[denom][$index].' = '.($qty[$index]*$denom[$index]).'<br>';
}
}
Here's the array I have, any help would be much appreciate, I'm usually great at this bot it's driving me crazy
Array
(
[2] => Array
(
[total] => 105
[denom] => Array
(
[0] => 105
)
[qty] => Array
(
[0] => 1
)
)
[3] => Array
(
[total] => 210
[denom] => Array
(
[0] => 105
)
[qty] => Array
(
[0] => 2
)
)
[4] => Array
(
[total] => 300
[denom] => Array
(
[0] => 300
)
[qty] => Array
(
[0] => 1
)
)
[5] => Array
(
[total] => 405
[denom] => Array
(
[0] => 300
[1] => 105
)
[qty] => Array
(
[0] => 1
[1] => 1
)
)
[6] => Array
(
[total] => 500
[denom] => Array
(
[0] => 500
)
[qty] => Array
(
[0] => 1
)
)
[7] => Array
(
[total] => 605
[denom] => Array
(
[0] => 500
[1] => 105
)
[qty] => Array
(
[0] => 1
[1] => 1
)
)
Constant non-numeric array indices should be written like any other string, i.e. encapsulated in quotes.
foreach($array as $arr) {
echo '<input type="radio" name="name" value="'.$arr['total'].'">';
foreach($arr['denom'] as $index => $d){
for ($j = 0;$j < count($denom);$j++) {
echo $d['qty'][$j].' x '.$d['denom'][$j].' = ';
echo ($d['qty'][$j]*$d['denom'][$j]) . '<br>';
}
}
}
First format your array like this in my code, add 6, 7 array elements. I modify for loop too.
<?php
$array = array(2 => array('total' => 105, 'denom' => array(0 => 105), 'qty' => array(0 => 1)),
3 => array('total' => 210, 'denom' => array(0 => 105), 'qty' => array(0 => 2)),
4 => array('total' => 300, 'denom' => array(0 => 300), 'qty' => array(0 => 1)),
5 => array('total' => 405, 'denom' => array(0 => 300, 1 => 105), 'qty' => array(0 => 1, 1 => 1)),
);
foreach($array as $arr)
{
//var_dump($arr);
echo '<input type="radio" name="name" value="'.$arr['total'].'">';
foreach($arr['denom'] as $index => $d)
{
echo $arr['qty'][$index].' x '.$d.' = '.($arr['qty'][$index]*$d).'<br>';
}
}
?>

Categories