Nickool
Nickool

Reputation: 3702

sort based on other array multi dimentional

I have products that have id,color and cable size.I want to respect the order of cable size array with product ids like this:

cable Array
(
    [5619] => 10 - Inch
    [5552] => 10 - Foot
    [8211] => 10 - Inch
    [5733] => 10 - Foot
)

so this cable array is like our sort map what ever product we have in this example should have 10-inch first and 10-foot next and they come with the product ids.

then I have colors

product Array
(

    [Green] => Array
        (
            [5552] => 10 - Foot
            [5619] => 10 - Inch
        )

    [Pink] => Array
        (
            [5733] => 10 - Foot
            [8211] => 10 - Inch
        )

    [Black] => Array
        (
            [4564] => 10 - Foot
        )

)

in this example, when we have more than one size for a color it should be ordered based on the cable array pink and green should be:

[Pink] => Array
        (
            [8211] => 10 - Inch
            [5733] => 10 - Foot

        )
because 8211 came before 5733 in cable array.
[Green] => Array
            (
             [5619] => 10 - Inch   
             [5552] => 10 - Foot
            )
 as well because 5619 came before 5552 in cable array.

I did this:

function OrderSizeAndColorByMerging($cablesizes, $productarray) {
    foreach ($cablesizes as $id => $size):
        foreach ($productarray as $color => $sizes):
            if ($sizes[$id]):
                $productarray[$color] = $cablesizes;
            endif;
        endforeach;
    endforeach;
    return $productarray;
}

but it is wrong, not sure how I can achieve it.

Upvotes: 1

Views: 47

Answers (2)

Nickool
Nickool

Reputation: 3702

as QuakeCore mentioned in his code I had to unset the array inside of colors and then assign them again. so now my code is working, hope it can help some peers in future:

function OrderSizeAndColorByMerging($cablesizes, $productarray) {

    foreach ($cablesizes as $id => $size):
        foreach ($productarray as $color=>$array):
    if (array_key_exists($id, $array)) {
         unset($productarray[$color][$id]);
         $productarray[$color][$id]=$size;
            }
        endforeach;
    endforeach;

    return $productarray;
}

Upvotes: 0

QuakeCore
QuakeCore

Reputation: 1926

   foreach( $cable as $key => $value ){
      foreach ($product as $keyarray){

    if (array_key_exists( $key , $keyarray ))
    {
    echo array_key_exists( $key , $keyarray );
    unset($keyarray[$key]);
    array_unshift($arr ,$key=>value);// not sure if this is ever going to work, but i am giving u a general idea (never tested it)
    break;
    }
    }
    }
    print_r($array2);

Upvotes: 1

Related Questions