0

I have a question regarding this problem (as per title). This is my array

Array
(
    [0] => Array
        (
            [0] => 0
            [1] => 0
        )

    [1] => Array
        (
            [0] => 3
            [1] => 2
        )

    [2] => Array
        (
            [0] => 1
            [1] => 0
        )
)

for more detail, you can see the picture Multidimensional Array

The first dimensional will always have the same length (in this case is 3). What I want to achieve is : I want to fetch the data from this multidimensional array so I can use the value to update my database. The syntax would be like this (I will using loop):

$sql = "UPDATE table_name SET column1='".$body[$i]."', column2='".$grip[$i]."', column3='".$gear[$i]."' WHERE `variant`='".$variant[$i]."'";

Is it possible? In this case, the variant column will be A,B.

I already saw these question

but I still don't understand.

This is my code

 if ($stmt2 = $conn->prepare("SELECT * FROM ms WHERE variant in (SELECT variant FROM pwhorder WHERE times = '$time' AND NOT quantity = 0)")) {
   $stmt2->execute();
   $result2 = $stmt2->get_result();
   $num_of_rows2 = $result2->num_rows;
   while ($row2 = $result2->fetch_assoc()) {
       $amountb1[]=$row2["amount1"];
       $amountb2[]=$row2["amount2"];
       $amountb3[]=$row2["amount3"];
   }
   $stmt2->free_result();
   $stmt2->close();
}

$stock=array($amountb1,$amountb2,$amountb3);

I do this because at first I want to compare $stock with $request. The code for $request is similar with $stock, it is just taken from different table.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Theo
  • 33
  • 6

1 Answers1

0

This seems like a perfect case in which associative arrays would solve your problem nicely. However since you stated the problem is utilizing indexed arrays, you would need to step through each array and perform actions, however you'll have to maintain a companion array of values for the interpretation of the indexes to their keys.

Start with your lookup arrays to be a companion to your data.

$top_level = array('Body', 'Grip', 'Gear');
$second_level = array('A','B');

Then you will want to process your data array and store into it's associated companioned keyed array.

So let's say your multidimensional array would be name $data

for( $d = 0 ; $d < count($data); $d++ )
{
    for( $s = 0; $s < count($data[$d]); $s++ )
    {
        $output[$top_level[$d]][$second_level[$s]] = $data[$d][$s];
    }//END FOR S < DATA{D}
}//END FOR D < COUNT(DATA)

Now this is currently untested code (I'm not within reach of a PHP compiler for testing). If you do get any errors drop a comment and I'd be happy to update.

The resulting $output array should be the formatted data you are looking for if I am understanding you correctly.

Danoweb
  • 423
  • 2
  • 9