Solved

chek value and create a new array php

Posted on 2011-02-27
11
294 Views
Last Modified: 2012-06-21
Hi EE
i have an array as example, i must  chek two  value and create a news array.
This my master array:
Array
(
    [0] => Array
        (
            [pos] => 008
            [qty] => 1
            [orn1] => 75        
        )

    [1] => Array
        (
            [pos] => 008
            [qty] => 1
            [orn1] =>          
        )

    [2] => Array
        (
            [pos] => 007
            [qty] => 1
            [orn1] =>          
        )

    [3] => Array
        (
            [pos] => 007
            [qty] => 1
            [orn1] =>          
        )

)

I chek the [pos] and [orn1] and its is the same, need a new array add the [qty] value... like this

Array
(
    [0] => Array
        (
            [pos] => 008
            [qty] => 1
            [orn1] => 75        
        )

    [1] => Array
        (
            [pos] => 008
            [qty] => 1
            [orn1] =>          
        )

    [2] => Array
        (
            [pos] => 007
            [qty] => 2
            [orn1] =>          
        )
)
0
Comment
Question by:denny3d
  • 4
  • 4
  • 3
11 Comments
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 34991940
Try this

<?php

function compressArray( $arr ) {
     $newArray = array();

     foreach( $arr as $anItem ) {

          // inspect newArray looking for a match.
          //
          $found = false;
          for ( $i=0; $i < count($newArray); $i++ ) {
               if ( $anItem['pos'] == $newArray[$i]['pos'] && $anItem['orn1'] == $newArray[$i]['orn1'] ) {
                    $newArray[$i]['qty']++;
                    $found = true;
                    break;
               }          
          }

          if ( ! $found ) {
               $a = array();
               $a['pos']  = $anItem['pos'];
               $a['qty']  = 1;
               $a['orn1'] = $anItem['orn1'];
               $newArray [] = $a;
          }

     }

     return $newArray;
}



$arr = array(
               array( 'pos' => '007', 'qty' => 1, 'orn1' => 75 ),
               array( 'pos' => '007', 'qty' => 1, 'orn1' => '' ),
               array( 'pos' => '008', 'qty' => 1, 'orn1' => '' ),
               array( 'pos' => '008', 'qty' => 1, 'orn1' => '' )
            );


print_r( compressArray( $arr ) );

Open in new window

0
 
LVL 109

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 34991999
You can see the test here:
http://www.laprbass.com/RAY_temp_denny3d.php
<?php // RAY_temp_denny3d.php
error_reporting(E_ALL);
echo "<pre>";

// TEST DATA FROM THE POST AT EE
$old = Array
(
    0 => Array
        (
            "pos" => "008",
            "qty" => 1,
            "orn1" => 75,
        ),

    1 => Array
        (
            "pos" => "008",
            "qty" => 1,
            "orn1" => '',
        ),

    2 => Array
        (
            "pos" => "007",
            "qty" => 1,
            "orn1" => '',
        ),

    3 => Array
        (
            "pos" => "007",
            "qty" => 1,
            "orn1" => '',
        ),
)
;
print_r($old);


// CREATE A NEW ARRAY CONTAINING BOTH pos AND orn1 IN A SINGLE FIELD
$mid = array();
foreach ($old as $sub_array)
{
    $pos_orn1 = $sub_array["pos"] . '_' . $sub_array["orn1"];

    $mid_sub_array
    = array
    ( "pos"      => $sub_array["pos"]
    , "qty"      => $sub_array["qty"]
    , "orn1"     => $sub_array["orn1"]
    , "pos_orn1" => $pos_orn1
    )
    ;
    $mid[] = $mid_sub_array;
}


// MAYBE WE WANT TO SORT THE ARRAY?
usort($mid, 'my_sort');

// THE USORT THAT ORDERS THE ARRAY ON pos_orn1
// A FUNCTION TO COMPARE BY NAMES
function my_sort($a, $b)
{
    if ($a["pos_orn1"] == $b["pos_orn1"]) return 0;
    return ($a["pos_orn1"] < $b["pos_orn1"]) ? -1 : 1;
}
print_r($mid);


// RUN THROUGH THE ARRAY TO AGGREGATE THE VALUES
$xyz = array();
foreach ($mid as $sub_array)
{
    $pos_orn1 = $sub_array["pos_orn1"];
    $qty      = $sub_array["qty"];
    $xyz[$pos_orn1] = @$xyz[$pos_orn1] + $qty;
}


// CREATE THE NEW ARRAY
$new = array();
foreach ($xyz as $pos_orn1 => $qty)
{
    $arr  = explode('_', $pos_orn1);
    $pos  = $arr[0];
    $orn1 = $arr[1];
    $new_sub_array = array
    ( "pos"  => $pos
    , "qty"  => $qty
    , "orn1" => "$orn1"
    )
    ;
    $new[] = $new_sub_array;
}
print_r($new);

Open in new window

0
 

Author Comment

by:denny3d
ID: 35007539
Hi bportlock
your reply is not ok, because I need the sum of value qty.
0
ScreenConnect 6.0 Free Trial

At ScreenConnect, partner feedback doesn't fall on deaf ears. We collected partner suggestions off of their virtual wish list and transformed them into one game-changing release: ScreenConnect 6.0. Explore all of the extras and enhancements for yourself!

 

Author Comment

by:denny3d
ID: 35007589
Hi ray
your reply is ok , but i have any request.
reality in my array I have other value that i need into final array.
The start array is:
$old = Array
(
    0 => Array
        (
            "pos" => "008",
            "qty" => 1,
            "orn1" => 75,
            "com" => "a",
        ),

    1 => Array
        (
            "pos" => "008",
            "qty" => 1,
            "orn1" => '',
            "com" => "a",
        ),

    2 => Array
        (
            "pos" => "007",
            "qty" => 1,
            "orn1" => '',
            "com" => "b",
        ),

    3 => Array
        (
            "pos" => "007",
            "qty" => 1,
            "orn1" => '',
            "com" => "b",
        ),
)
;

I need value com into final array, how I insert it?
I try to modify the code, but into array $xyz i dont have the value

regards

0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35007600
"....I need the sum of value qty."

????

You never mentioned this in the question. Exactly what do you mean? Do you just want all the qty numbers added together?
0
 

Author Comment

by:denny3d
ID: 35007680
Yes, example, if qty value is 1 and 1 , its ok 2, but if the value is 2 and 3 i need value 5
Sorry for my bad english

0
 
LVL 34

Assisted Solution

by:Beverley Portlock
Beverley Portlock earned 250 total points
ID: 35007879
Altered code below. I have changed the qty figures in the test data to illustrate the code

<?php

function compressArray( $arr ) {
     $newArray = array();

     foreach( $arr as $anItem ) {

          // inspect newArray looking for a match.
          //
          $found = false;
          for ( $i=0; $i < count($newArray); $i++ ) {
               if ( $anItem['pos'] == $newArray[$i]['pos'] && $anItem['orn1'] == $newArray[$i]['orn1'] ) {
                    $newArray[$i]['qty'] += $anItem['qty'];
                    $found = true;
                    break;
               }
          }

          if ( ! $found ) {
               $a = array();
               $a['pos']  = $anItem['pos'];
               $a['qty']   = $anItem['qty'];
               $a['orn1'] = $anItem['orn1'];
               $newArray [] = $a;
          }

     }

     return $newArray;
}



$arr = array(
               array( 'pos' => '007', 'qty' => 1, 'orn1' => 75 ),
               array( 'pos' => '007', 'qty' => 2, 'orn1' => '' ),
               array( 'pos' => '008', 'qty' => 3, 'orn1' => '' ),
               array( 'pos' => '008', 'qty' => 4, 'orn1' => '' )
            );


print_r( compressArray( $arr ) );

Open in new window

0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 35008942
It would be a lot easier to help you if you would give us the complete problem definition first, instead of changing the definition after you have posted the question and received an answer.  

A tested and working example that is responsive to your question was posted a couple of days ago at http:#34991999 
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 35009048
@Brian, notice the Asker's addition of another field, "com" at ID:35007589.  I think this question is answered and denny3d should open a new question to ask, "What is a better way of structuring my data?"  Your practice of creating an array of objects seems to be exactly what is needed here.  Then when the question changes in mid-stream, another property and/or method can be added to the object.

Over and out, ~Ray
0
 

Author Closing Comment

by:denny3d
ID: 35011357
Apologize for add a new value... this question is solved with each reply.
Now i open a new question with more details.
regards
0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35012449
Ray said: ".....Your practice of creating an array of objects seems to be exactly what is needed here. ..."

LOL - don't get me started...... but yes, that is why I use that technique, but a lot of people seem to be frightened of classes even for something as simple as data grouping. However since you have raised it I shall include a link for the OP

@denny3d - here is a link to an article I wrote some time ago. If you use this method to group data then it makes the addition of new data items a trivial matter. It removes the difficulties used by using arrays of arrays to manage data.

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_3212-Using-PHP-classes-to-group-data-in-memory.html
0

Featured Post

VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
This article discusses how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question