Solved

chek value and create a new array php

Posted on 2011-02-27
11
298 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 110

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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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 110

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 110

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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

734 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