how to group together arrays based on a value in php? - php

I have thee following $array:
Array
(
[0] => Array
(
[cd] => 1675
[amt_1] => 199.50
[fname] => Joe
[lname] => A
)
[1] => Array
(
[cd] => 1675
[amt_1] => 69.90
[fname] => Joe
[lname] => A
)
[2] => Array
(
[cd] => 1676
[amt_1] => 69.90
[fname] => Tracy
[lname] => A
)
[3] => Array
(
[cd] => 1676
[amt_1] => 199.50
[fname] => Tracy
[lname] => A
)
...
)
I am trying to do is to group them together, in this case, by fname or cd so that i will have something like:
[0] => Array
(
[cd] => 1676
Array
(
[0] => Array
(
[amt_1] => 199.50
)
[1] => Array
(
[amt_1] => 69.90
)
[fname] => Joe
[lname] => A
)
[1] => Array
(
[cd] => 1676
Array
(
[0] => Array
(
[amt_1] => 199.50
)
[1] => Array
(
[amt_1] => 69.90
)
[fname] => Tracy
[lname] => A
)
........
I can't seem to figure it out.
This cannot be done in mysql, I need to do it in php.
Any ideas?
Thanks
edit: I know that the result example is not formatted correct, but basically I want to combine the fname and the rest of results place them in arrays.
edit:
#Paulo H has a good idea. also i found another way of doing it that groups it together not combining it :
$groups = array ();
foreach ( $the_array as $item ) {
$key = $item ['fname'];
if (! isset ( $groups [$key] )) {
$groups [$key] = array ('items' => array ($item ), 'count' => 1 );
} else {
$groups [$key] ['items'] [] = $item;
$groups [$key] ['count'] += 1;
}
}

Try this:
function &array_group_value_by($input_array,$value,$by){
$result = array();
foreach($input_array as $array){
if(!isset($result[$array[$by]])){
$result[$array[$by]] = array();
}
foreach($array as $key=>$data){
if((is_string($value) && $key==$value) || (is_array($value) && in_array($key,$value))){
if(!isset($result[$array[$by]][$key])){
$result[$array[$by]][$key] = array();
}
$result[$array[$by]][$key][] = $data;
}else{
$result[$array[$by]][$key] = $data;
}
}
}
return $result;
}
$grouped = array_group_value_by($yourarray,'amt_1','fname');
print_r($grouped);

Related

Make an element in array explode

How to make an element array inside an array explode again.
I have an array like this
echo "<pre>";
print_r($pks);
The Result.
Array
(
[0] => 2017-04-15||KMTC_HOCHIMINH
[1] => 2017-04-15||OOCL_NAGOYA
)
I expected like this,
Array
(
[record] =>
[1] 2017-04-15
[2] KMTC_HOCHIMINH
[record] =>
[1] 2017-04-15
[2] OOCL_NAGOYA
)
What keys on php to process array like this.
Please advise.
UPDATE
How about this .
Array
(
[0] => Array
(
[date] => 2017-04-15
[vessel] => KMTC_HOCHIMINH
)
[1] => Array
(
[date] => 2017-04-15
[vessel] => OOCL_NAGOYA
)
)
Try this, check the live demo
foreach($pks as $k => $v) {
$values = explode('||', $v);
$result[] = array_combine(range(1, count($values)), $values);
//added
$res[] = array_combine(['date', 'vessel'], $values) ;
}
result
Array
(
[0] => Array
(
[1] => 2017-04-15
[2] => KMTC_HOCHIMINH
)
[1] => Array
(
[1] => 2017-04-15
[2] => OOCL_NAGOYA
)
)
You can use array_walk() (or just foreach if you want):
array_walk($pks, function(&$a) {
$a = array_combine(['date', 'vessel'], explode('||', $a));
});
Foreach method:
foreach($pks as $k => $v) {
$pks[$k] = array_combine(['date', 'vessel'], explode('||', $v));
}
However, the key of each array won't be record, since it's impossible to have the same key multiple times.
Output:
Array
(
[0] => Array
(
[date] => 2017-04-15
[vessel] => KMTC_HOCHIMINH
)
[1] => Array
(
[date] => 2017-04-15
[vessel] => OOCL_NAGOYA
)
)
Bonus method because I like messing with arrays:
$pks = array_map('explode', array_fill(0, count($pks), '||'), $pks);

PHP How to restructure an array?

I have an array that I'd like to restructure. I want to group items by turn. I can figure out how to extract data from the array using foreach($arr['history'] as $obj) my issue is with populating a new array using a loop.
Currently it looks like this:
Array (
[history] => Array (
[id] => 23452435
[legend] => Array (
[0] => Array (
[player] => me
[turn] => 1
[card] => Array (
[name] => foo
)
)
[1] => Array (
[player] => me
[turn] => 1
[card] => Array (
[name] => bar
)
)
[2] => Array (
[player] => opponent
[turn] => 1
[card] => Array (
[name] => derp
)
)
[3] => Array (
[player] => opponent
[turn] => 2
[card] => Array (
[name] => hoo
)
)
)
))
I want it to look like the following, but I can't figure out how to automatically create and populate this structure. This is an array with a sub-array for each turn, containing an array for me and opponent
Array (
[0] => Array (
[me] => Array (
[0] => foo
[1] => bar
)
[opponent] = Array (
[0] => derp
)
)
[1] => Array (
[me] => Array ()
[opponent] => Array (
[0] => hoo
)
))
Thanks.
Edit:
This is what I needed. Thanks for the answers.
$result = [];
foreach ($arr['history'] as $historyItem) {
foreach ($historyItem['legend'] as $list) {
$result[$list['turn']][$list['player']][] = $list['card']['name'];
}
}
Try this:
$result = [];
foreach ($data['history']['legend'] as $list) {
$result[$list['turn']-1][$list['player']][] = $list['card']['name'];
}
Fiddle it! http://ideone.com/BtKOKJ
You can just start adding data to the new array. PHP is extremely forgiving.
$historyByTurns = array();
foreach ($arr['history'] as $historyItem) {
foreach ($historyItem['legend'] as $legendItem) {
$turn = $legendItem['turn'];
$player = $legendItem['player'];
if (!array_key_exists($turn, $historyByTurns)) {
$historyByTurns[$turn] = array();
}
if (!array_key_exists($player, $historyByTurns[$turn])) {
$historyByTurns[$turn][$player] = array();
}
foreach ($legendItem as $card) {
$historyByTurns[$turn][$player][] = $card['name'];
}
}
}
You will have to test it, as I have no way to do that ATM.

Bulid for loop based on given array

I am generating dynamic textbox for save and add more functionality and i have to store that data in database i got the array but i dont know how to put that array in to loop so i can get my data.
Array looks like this based on this prepare loop so i can access every element of array:
Array
(
[0] => Array
(
[0] => Array
(
[0] => Array
(
[prem_type] => 1
)
[1] => Array
(
[phase_name] => a1
)
[2] => Array
(
[counter] => 2
)
[3] => Array
(
[block] => A
)
[4] => Array
(
[block] => B
)
)
)
[1] => Array
(
[0] => Array
(
[0] => Array
(
[prem_type] => 1
)
[1] => Array
(
[phase_name] => a2
)
[2] => Array
(
[counter] => 2
)
[3] => Array
(
[block] => A
)
[4] => Array
(
[block] => B
)
)
)
)
Thanks
try this
$array = //your array
foreach($array as $value){
foreach($value as $value2){
foreach($value2 as $value3){
foreach($value3 as $key3 => $value3){
//$key3 is rem_type, phase_nameā€¦
//$value3 is required values
}
}
}
}
To get to the data you can use something like:
foreach ($array AS $row) {
$prem_type = $row[0][0]['prem_type'];
$phase_name = $row[0][1]['phase_name'];
$counter = $row[0][2]['counter'];
$block1 = $row[0][3]['block'];
$block2 = $row[0][4]['block'];
}
An alternative is to restructure the array into something more tidy:
$result = array();
foreach ($array AS $rowId => $row) {
$result[$rowId] = array(
'prem_type' => $row[0][0]['prem_type'],
'phase_name' => $row[0][1]['phase_name'],
'counter' => $row[0][2]['counter'],
'block1' => $row[0][3]['block'],
'block2' => $row[0][4]['block']
);
}
This results in:
Array
(
[0] => Array
(
[prem_type] => 1,
[phase_name] => a1,
[counter] => 2,
[block1] => A,
[block2] => B
)
...
)
Here is the answer:
for($i=0;$i<count($data1);$i++){
for($j=0;$j<count($data1[$i]);$j++){
$prem_type =$data1[$i][$j][0]['prem_type'];
$prem_name= $data1[$i][$j][1]['phase_name'];
$no_of_phase= $data1[$i][$j][2]['counter'];
echo $prem_type." ".$prem_name." ".$no_of_phase."<br>";
for($k=3;$k<count($data1[$i][$j]);$k++){
echo $data1[$i][$j][$k]['unitname']."<br>";
}
}
}

how can i count an element if it appears more than once in the same array?

how can i count an element if it appears more than once in the same array?
I already tried with array_count_values, but it did not work, is it beacuse i got more than one key and value in my array?
This is my output from my array (restlist)
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla)
[1] => Array ( [restaurant_id] => 32144 [title] => test5)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
[3] => Array ( [restaurant_id] => 32144 [title] => test5)
[4] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
)
I want it to count how many times the same element appears in my array and then add the counted value to my newly created 'key' called hits in the same array.
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla [hits] => 1)
[1] => Array ( [restaurant_id] => 32144 [title] => test5 [hits] => 2)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 [hits] => 2)
)
This is how i tried to do what i wanted.
foreach ($cooltransactions as $key)
{
$tempArrayOverRestaurants[]= $key['restaurant_id'];
}
$wordsRestaruants = array_count_values($tempArrayOverRestaurants);
arsort($wordsRestaruants);
foreach ($wordsRestaruants as $key1 => $value1)
{
$temprestaurantswithhits[] = array(
'restaurant_id' => $key1,
'hits' => $value1);
}
foreach ($restlistas $key)
{
foreach ($temprestaurantswithhits as $key1)
{
if($key['restaurant_id'] === $key1['restaurant_id'])
{
$nyspisestedsliste[] = array(
'restaurant_id' => $key['restaurant_id'],
'title' => $key['title'],
'hits' => $key1['hits']);
}
}
}
I know this is probably a noob way to do what i want but i am still new at php..I hope you can help
Just try with associative array:
$input = array( /* your input data*/ );
$output = array();
foreach ( $input as $item ) {
$id = $item['restaurant_id'];
if ( !isset($output[$id]) ) {
$output[$id] = $item;
$output[$id]['hits'] = 1;
} else {
$output[$id]['hits']++;
}
}
And if you want to reset keys, do:
$outputWithoutKeys = array_values($output);

Removing a key=>value pair from a 3D associative array - PHP

The 3D assoc. array looks like below.
Array
(
[COL] => Array
(
[0] => Array
(
[emp_num] => 1000001
[user_name] => Test User
[amount] => 775.00
[name] => COL
)
[1] => Array
(
[emp_num] => 26
[user_name] => John Doe
[amount] => 555.00
[name] => COL
)
)
[RA. 20%] => Array
(
[0] => Array
(
[emp_num] => 1000001
[user_name] => Test User
[amount] => 110.00
[name] => RA. 20%
)
)
[BS] => Array
(
[0] => Array
(
[emp_num] => 1000001
[user_name] => Test User
[amount] => 444.00
[name] => BS
)
)
)
I want to remove the the last key=>value pair of each inner most array. (want to remove the key value pair that has [name] for the key)
The result should look like the array below.
Array
(
[COL] => Array
(
[0] => Array
(
[emp_num] => 1000001
[user_name] => Test User
[amount] => 775.00
)
[1] => Array
(
[emp_num] => 26
[user_name] => John Doe
[amount] => 555.00
)
)
[RA. 20%] => Array
(
[0] => Array
(
[emp_num] => 1000001
[user_name] => Test User
[amount] => 110.00
)
)
[BS] => Array
(
[0] => Array
(
[emp_num] => 1000001
[user_name] => Test User
[amount] => 444.00
)
)
)
I wrote a function to do this.
<!-- language: php -->
function remove_name_from_psa($psa_array){
foreach( $psa_array as $key=>$value ) {
foreach( $value as $key2=>$value2 ){
foreach( $value2 as $key3=>$value3 ){
if( $key3 != 'name') {
$psa_name_removed[$key][$value[$key2][$value2[$key3]]] = $value3;
}
}
}
}
return $psa_name_removed;
}
The returned array is this, which is obviously not what I need.
Array ( [COST OF LIVING] => Array
( [] => 555.00 )
[RENT ALLOW. 20%] => Array
( [] => 110.00 )
[BASIC SALARY] => Array
( [] => 444.00 )
)
And there are lots of undefined offset and undefined index notices.
$psa_name_removed[$key][$value[$key2][$value2[$key3]]] = $value3; //is this the line I am doing the mistake? Or is the whole method a mistake? :-P
How can I get this to work? Can anyone help?
Thank You!
function remove_name_from_psa($psa_array){
foreach( $psa_array as $key => $value ) {
foreach( $value as $key2 => $value2 ){
unset( $psa_array[$key][$key2]['name'] );
}
}
return $psa_array;
}
Wee, functional solution!
$array = array_map(function ($i) {
return array_map(function ($j) {
return array_diff_key($j, array_flip(array('name')));
}, $i);
}, $array);
More traditional solution:
foreach ($array as &$i) {
foreach ($i as &$j) {
unset($j['name']);
}
}
Note the & in as &$i. Use this reference to modify the item.
foreach($array as &$foo){
foreach($foo as &$bar){
unset($bar['name']);
}
}
To truly unset the last element in a 3D array your would do this:
$data = array(
array(
array(1, 2, 3),
),
);
foreach ($data as $i1 => $j1) {
foreach ($j1 as $i2 => $j2) {
end($j2);
unset($data[$i1][$i2][key($j2)]);
}
}
var_dump($data);
See it in action here:
http://codepad.viper-7.com/CbgnVf
function remove_name_from_psa( $psa_array ){
foreach( $psa_array as $key => $value ) {
foreach( $value as $key2 => $value2 ) {
array_pop( $psa_array[$key][$key2] );
}
}
return $psa_array;
}

Categories