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
Solved

chek value and create a new array php

Posted on 2011-02-27
11
296 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
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
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…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

840 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