This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 6 years ago.
I am trying to get values for each field eg. translation in subarrays without foreach. Is it possible?
Array
(
[0] => Array
(
[group_id] => 11
[group_translation] => Extras
[id] => 21
[operation] => +
[price] => 5
[price_by] => once
[price_type] => fixed
[translation] => Pick up
[price_total] => 5
)
[1] => Array
(
[group_id] => 11
[group_translation] => Extras
[id] => 22
[operation] => +
[price] => 10
[price_by] => once
[price_type] => fixed
[translation] => Drinks
[price_total] => 10
)
)
Thank you!
Sure that is possible:
<?php
$data = [
[
'group_id' => 11,
'group_translation' => 'Extras',
'id' => 21,
'operation' => '+',
'price' => 5,
'price_by' => 'once',
'price_type' => 'fixed',
'translation' => 'Pick up',
'price_total]' => 5
],
[
'group_id' => 11,
'group_translation' => 'Extras',
'id' => 22,
'operation' => '+',
'price' => 10,
'price_by' => 'once',
'price_type' => 'fixed',
'translation' => 'Drinks',
'price_total' => 10
]
];
$extract = [];
array_walk($data, function($element) use (&$extract) {
$extract[] = $element['translation'];
});
var_dump($extract);
The output obviously is:
array(2) {
[0] =>
string(7) "Pick up"
[1] =>
string(6) "Drinks"
}
Related
I have an array like below. There are id, label, cost, and cid in an array. We want to sum the cost based on the cid like for cid 22 cost should be 196.5 and for cid 11 cost should be 44.4. In our out put array we want to keep the label, cost (sum), and cid, Please see expected output array.
Array
(
[0] => Array
(
[id] => 1331
[label] => PM1
[cost] => 98.25
[cid] => 22
[product_id] => 133
)
[1] => Array
(
[id] => 1332
[label] => PM3
[cost] => 22.20
[cid] => 11
[product_id] => 133
)
[2] => Array
(
[id] => 1341
[label] => PM1
[cost] => 98.25
[cid] => 22
[product_id] => 134
)
[3] => Array
(
[id] => 1342
[label] => PM3
[cost] => 22.20
[cid] => 11
[product_id] => 134
)
)
Tried below
foreach ($array $key => $value) {
$final[$value['cid']] += $value['cost'];
}
print_r ($final);
Getting below as an output
Array
(
[22] => 196.5
[11] => 44.4
)
Want expected output like below.
Array
(
[22] => Array
(
[label] => PM1
[cost] => 196.5
[cid] => 22
)
[11] => Array
(
[label] => PM3
[cost] => 44.4
[cid] => 11
)
)
Basically want to sum cost based on cid and want to keep the label, cost (sum), and cid.
Any help will be greatly appreciated.
I believe this should do the trick
$CIDs_identified = array();
$final_array = array();
foreach($original_array as $small_array){
if(!in_array($small_array['cid'], $CIDs_identified)){
$CIDs_identified[] = $small_array['cid'];
$final_array[$small_array['cid']] = array(
'label' => $small_array['label'],
'cost' => $small_array['cost'],
'cid' => $small_array['cid'],
);
}else{
$final_array[$small_array['cid']]['cost'] += $small_array['cost'];
}
}
On this site, if you can provide your source array in usable format, that is really helpful so that we don't have to retype it. One way to do that is using var_export.
Below is a simple version. Create an array indexed by cid. If that item doesn't exist, populate it with the basic data and a zero cost. Then on each loop, including the initial, add the row's cost.
<?php
$data = [
[
'id' => 1331,
'label' => 'PMI',
'cost' => 98.25,
'cid' => 22,
'product_id' => 133,
],
[
'id' => 1341,
'label' => 'PMI',
'cost' => 98.25,
'cid' => 22,
'product_id' => 134,
],
];
$output = [];
foreach ($data as $item) {
if (!isset($output[$item['cid']])) {
$output[$item['cid']] = [
'label' => $item['label'],
'cost' => 0,
'cid' => $item['cid'],
];
}
$output[$item['cid']]['cost'] += $item['cost'];
}
print_r($output);
Demo here: https://3v4l.org/MY6Xu
$list = [
[ 'id' => 1331, 'label' => 'PM1', 'cost' => 98.25, 'cid' => 22, 'product_id' => 133 ],
[ 'id' => 1332, 'label' => 'PM3', 'cost' => 22.20, 'cid' => 11, 'product_id' => 133 ],
[ 'id' => 1341, 'label' => 'PM1', 'cost' => 98.25, 'cid' => 22, 'product_id' => 134 ],
[ 'id' => 1342, 'label' => 'PM3', 'cost' => 22.20, 'cid' => 11, 'product_id' => 134 ]
];
$result = [];
array_walk($list, function ($item) use (&$result) {
if (isset($result[$item['cid']])) {
$result[$item['cid']]['cost'] = $item['cost'] + $result[$item['cid']]['cost'];
} else {
$result[$item['cid']] = [ 'label' => $item['label'], 'cost' => $item['cost'], 'cid' => $item['cid'] ];
}
});
print_r($result);
Output:
Array
(
[22] => Array
(
[label] => PM1
[cost] => 196.5
[cid] => 22
)
[11] => Array
(
[label] => PM3
[cost] => 44.4
[cid] => 11
)
)
This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed last year.
This is the result of dd() that I use in my controller on laravel 8. I want to sort the data based on the JB column. I can't use the manual order by in SQL syntax because I get JB from complex DB RAW. Therefore I want to sort this multi-dimensional array using php. Does anyone know how to sort the multi-dimensional array based on JB column value?
here I go...
you can use array_multisort PHP function. Link
$new = [
[
'id' => 13,
'name' => 'Tony',
'jb' => 3,
],
[
'id' => 15,
'name' => 'Joe',
'jb' => 2,
],
[
'id' => 16,
'name' => 'Ross',
'jb' => 1,
],
[
'id' => 18,
'name' => 'Monika',
'jb' => 5,
],
[
'id' => 20,
'name' => 'Joye',
'jb' => 7,
],
];
$keys = array_column($new, 'jb');
array_multisort($keys, SORT_ASC, $new);
so as a result you will get link,
Array
(
[0] => Array
(
[id] => 16
[name] => Ross
[jb] => 1
)
[1] => Array
(
[id] => 15
[name] => Joe
[jb] => 2
)
[2] => Array
(
[id] => 13
[name] => Tony
[jb] => 3
)
[3] => Array
(
[id] => 18
[name] => Monika
[jb] => 5
)
[4] => Array
(
[id] => 20
[name] => Joye
[jb] => 7
)
)
sortBy method solves your issue. Laravel really has a strong bunch of methods in collections. Below code block shows an example.
$collection = collect([
['name' => 'Desk', 'price' => 200],
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
]);
$sorted = $collection->sortBy('price');
$sorted->values()->all();
/*
[
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
['name' => 'Desk', 'price' => 200],
]
*/
I am trying to change the following array to an almost flat array. So id 4 would be in the first level of the array, as would id 6 and 5, but still have their own index so I can tell which page is which. But with the same order as they have now. I presume that the solution would be some sort of recursive PHP function but I haven't a clue how to do this.
Array
(
[0] => Array
(
[id] => 2
[identifier] => External URL
[parent] => 0
[sortOrder] => 1
[depth] => 0
)
[1] => Array
(
[id] => 3
[identifier] => First Team
[parent] => 0
[sortOrder] => 2
[depth] => 0
[children] => Array
(
[0] => Array
(
[id] => 4
[identifier] => League tables
[parent] => 3
[sortOrder] => 0
[depth] => 1
[children] => Array
(
[0] => Array
(
[id] => 6
[identifier] => British and Irish Cup Tables
[parent] => 4
[sortOrder] => 24
[depth] => 2
)
[1] => Array
(
[id] => 5
[identifier] => Greene King IPA Championship
[parent] => 4
[sortOrder] => 25
[depth] => 2
)
)
)
)
)
[2] => Array
(
[id] => 1
[identifier] => Home
[parent] => 0
[sortOrder] => 25
[depth] => 0
)
)
<?php
$data = [
[
'id' => 1,
'name' => 'one',
'children' =>
[
[
'id' => 2,
'name' => 'two',
'children' =>
[
[
'id' => 4,
'name' => 'four'
]
]
],
[
'id' => 3,
'name' => 'three',
'children' =>
[
[
'id' => 5,
'name' => 'five'
]
]
]
]
],
[
'id' => 6,
'name' => 'six'
]
];
$stanley = [];
$flatten = function(array $data) use (&$flatten, &$stanley) {
foreach($data as $k => $v) {
if(isset($v['children'])) {
$flatten($v['children']);
unset($v['children']);
}
$stanley[] = $v;
}
};
$flatten($data);
var_export($stanley);
Output:
array (
0 =>
array (
'id' => 4,
'name' => 'four',
),
1 =>
array (
'id' => 2,
'name' => 'two',
),
2 =>
array (
'id' => 5,
'name' => 'five',
),
3 =>
array (
'id' => 3,
'name' => 'three',
),
4 =>
array (
'id' => 1,
'name' => 'one',
),
5 =>
array (
'id' => 6,
'name' => 'six',
),
)
I have found the solution! I built a recursive PHP function which utilised the depth index to track which level each of the items are while still keeping the array flat (ish).
function dropdownNavigationTree($array) {
$response = [];
foreach($array as $page) {
if (!is_array($page['children'])) {
$response[$page['id']] = ($page['depth'] > 0 ? str_repeat("-", $page['depth']).' ' : FALSE).$page['identifier'];
} else {
$response[$page['id']] = ($page['depth'] > 0 ? str_repeat("-", $page['depth']).' ' : FALSE).$page['identifier'];
$children = dropdownNavigationTree($page['children']);
$response = $response + $children;
}
}
return $response;
}
I have the following array which I am getting as mysql result set
Array
(
[0] => Array
(
[slug] => block_three_column
[title] => CSG 2
[type_id] => 8
[entry_id] => 6
[stream_id] => 11
)
[1] => Array
(
[slug] => block_three_column
[title] => CSG
[type_id] => 8
[entry_id] => 5
[stream_id] => 11
)
)
Array
(
[0] => Array
(
[slug] => block_three_column
[title] => CSG 2
[type_id] => 8
[entry_id] => 6
[stream_id] => 11
)
[1] => Array
(
[slug] => block_three_column
[title] => CSG
[type_id] => 8
[entry_id] => 5
[stream_id] => 11
)
)
The both arrays are similar I want get the unique entry id using php.
I tried with the following code but it is producing 2 arrays again.
foreach($block_results as $rowarr)
{
foreach($rowarr as $k=>$v)
{
if($k == "entry_id")
{
$entid[] = $v;
}
}
}
Any help is highly appreciated. Thanks in advance.
You can use array_map() instead of foreach(). Example:
$entry_ids = array_unique(
array_map(
function($v){
return $v['entry_id'];
},
$array
)
);
var_dump($entry_ids);
array_unique() is to remove duplicate elements from array().
You can get the entry_id directly:
$array = array(
array(
'slug' => 'block_three_column',
'title' => 'CSG 2',
'type_id' => 8,
'entry_id' => 6,
'stream_id' => 11
),
array(
'slug' => 'block_three_column',
'title' => 'CSG',
'type_id' => 8,
'entry_id' => 5,
'stream_id' => 11
)
);
foreach ($array as $innerArray) {
if (isset($innerArray['entry_id'])) {
$entid[] = $innerArray['entry_id'];
}
}
var_dump($entid);
Output is:
array
0 => int 6
1 => int 5
Assuming that you want a list of the unique values of entry_id from the array, and it is possible that some will not have an entry_id set:
$entid = array();
foreach ( $array as $blockArray) {
if ( isset( $blockArray['entry_id'] )
&& !in_array( $blockArray['entry_id'], $entid ) ) {
$entid[] = $blockArray['entry_id'];
}
}
var_dump( $entid );
Try this:
PHP
$entid = array(); //Holds unique id's
foreach($block_results as $rowarr)
{
//Make sure entry_id exists
$entid[] = array_key_exists('entry_id',$rowarry) ? $rowarr['entry_id'] : false;
}
If they are always similiar and the same length:
foreach ($array1 as $key => $value) {
$firstValue = $array1[$key]['entry_id'];
$secondValue = $array2[$key]['entry_id'];
}
Though, keep in mind this solution is very sensitive to errors.
try this like your code:
$block_results = array(
array(
'slug' => 'block_three_column',
'title' => 'CSG 2',
'type_id' => 8,
'entry_id' => 6,
'stream_id' => 11
),
array(
'slug' => 'block_three_column',
'title' => 'CSG',
'type_id' => 8,
'entry_id' => 6,
'stream_id' => 11
),
array(
'slug' => 'block_three_column',
'title' => 'CSG',
'type_id' => 8,
'entry_id' => 7,
'stream_id' => 11
)
);
var_dump($block_results);
$entid=array();
if(count($block_results)>0)foreach($block_results as $rowarr)
{
$entid[] = $rowarr['entry_id'];
}
$entid=array_unique($entid);
var_dump($entid);
output:
array
0 =>
array
'slug' => string 'block_three_column' (length=18)
'title' => string 'CSG 2' (length=5)
'type_id' => int 8
'entry_id' => int 6
'stream_id' => int 11
1 =>
array
'slug' => string 'block_three_column' (length=18)
'title' => string 'CSG' (length=3)
'type_id' => int 8
'entry_id' => int 6
'stream_id' => int 11
2 =>
array
'slug' => string 'block_three_column' (length=18)
'title' => string 'CSG' (length=3)
'type_id' => int 8
'entry_id' => int 7
'stream_id' => int 11
array
0 => int 6
2 => int 7
I have the following array:
Array
(
[0] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[1] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[2] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[3] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[4] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[5] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[6] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
[7] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
[8] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
)
Which is being created with the following code:
$Display_Arr = array();
$Tick = 0;
foreach ($_POST['product'] AS $_1){
if (!in_array($_1['vendor_id'], $Display_Arr)){
$Display_Arr[$Tick] = array(
"Vendor_ID" => $_1['vendor_id'],
"Quantity" => ""
);
$Display_Arr[$Tick]["Quantity"] .= $_1['quantity'];
}else{
$Display_Arr[$Tick]["Quantity"] .= $_1['quantity'];
}
++$Tick;
}
echo "<pre>";
print_r($Display_Arr);
echo "</pre>";
But I am not getting my desired output, which is:
Array
(
[0] => Array
(
[Vendor_ID] => 1
[Quantity] => 55,55,55
)
[1] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[2] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
)
Where am I going wrong with this?
#mathielo
The current output is:
Array
(
[1] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[3] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[4] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
)
Whereas, i'm trying to obtain:
[0] => Array
(
[Vendor_ID] => 1
[Quantity] => 55,55,55
)
If I got it right, what you need is this:
EDIT: Just made some tests and got it right this time:
$Display_Arr = array();
foreach ($_POST['product'] AS $_1){
if (!array_key_exists($_1['Vendor_ID'], $Display_Arr)){
$Display_Arr[$_1['Vendor_ID']] = array(
"Vendor_ID" => $_1['Vendor_ID'],
"Quantity" => $_1['Quantity']
);
}else{
if(!empty($_1['Quantity']))
$Display_Arr[$_1['Vendor_ID']]["Quantity"] .= ",{$_1['Quantity']}";
}
}
echo "<pre>";
print_r($Display_Arr);
echo "</pre>";
The main problem was in if (!in_array($_1['vendor_id'], $Display_Arr)). PHP's in_array() checks for given needle in the array values, and we were trying to match to the Vendor_ID value stored in the outer array keys. That was fixed using array_key_exists().
EDIT 2: I used this for test data:
$_POST['product'] = array(
0 => array(
'Vendor_ID' => 1,
'Quantity' => 55
),
1 => array(
'Vendor_ID' => 1,
'Quantity' => 55
),
2 => array(
'Vendor_ID' => 1,
'Quantity' => 55
)
,
3 => array(
'Vendor_ID' => 3,
'Quantity' => ''
),
4 => array(
'Vendor_ID' => 3,
'Quantity' => ''
),
5 => array(
'Vendor_ID' => 3,
'Quantity' => ''
),
6 => array(
'Vendor_ID' => 4,
'Quantity' => ''
),
7 => array(
'Vendor_ID' => 4,
'Quantity' => ''
),
8 => array(
'Vendor_ID' => 4,
'Quantity' => ''
)
);
You won't be needing $Tick anymore, as you could use Vendor_ID as keys for the outer array.
Looks like the easiest way to solve this would be to first aggregate the vendor quantities, and then build the final array with the keys that you are using.
I am assuming the input looks something like this:
$_POST['product'] = [
['vendor_id' => 1, 'quantity' => 55],
['vendor_id' => 1, 'quantity' => 55],
['vendor_id' => 1, 'quantity' => 55],
['vendor_id' => 3, 'quantity' => null],
['vendor_id' => 3, 'quantity' => null],
['vendor_id' => 3, 'quantity' => null],
['vendor_id' => 4, 'quantity' => null],
['vendor_id' => 4, 'quantity' => null],
['vendor_id' => 4, 'quantity' => null],
];
Aggregating the quantities:
$aggregates = [];
foreach ($_POST['product'] as $product) {
$id = $product['vendor_id'];
if ( ! isset($aggregates[$id])) {
$aggregates[$id] = [];
}
if ($product['quantity'] > 0) {
$aggregates[$id][] = $product['quantity'];
}
}
The aggregates array should now look like this:
$aggregates = [
1 => [
0 => 55,
1 => 55,
2 => 55,
],
3 => [], // Empty
4 => [], // Empty
];
As you can see the data is now neatly organized and ready to be put into any format you want. Using the keys that you use in your question it is as simple as:
$output = [];
foreach ($aggregates as $vid => $qty) {
$quantity = implode(',', $qty);
$output[] = ['Vendor_ID' => $vid, 'Quantity' => $quantity];
}
The output should now look like this:
$output = [
['Vendor_ID' => 1, 'Quantity' => '55,55,55'],
['Vendor_ID' => 3, 'Quantity' => ''],
['Vendor_ID' => 4, 'Quantity' => ''],
];
This will output exactly what you are looking for although the output of the last answer (Sverri M. Olsen) is more useful. Here you get the quantities as a string while with Sverri's method you get an array in first place.
$Display_Arr = array();
$vendors=array();
foreach ($_POST['product'] AS $_1){
if (!in_array($_1['vendor_id'],$vendors)){
$vendors[]=$_1['vendor_id'];
$Display_Arr[sizeof($vendors)-1] = array(
"Vendor_ID" => $_1['vendor_id'],
"Quantity" => $_1['quantity']
);
}
else{
$vendorKey=array_search($_1['vendor_id'],$vendors);
$Display_Arr[$vendorKey]["Quantity"] .=(!empty($Display_Arr[$vendorKey]["Quantity"])?',':null).$_1['quantity'];
}
}