Foreach issue with json on multiple inserts

Discussion in 'PHP' started by xbat, Nov 8, 2017.

  1. #1
    I have a foreach then I have this code inside the foreach. I do aplogize about the incorrect wording.. If I change the [0] to [1] then [2] etc... it will insert the zero row then first row and 2 etc.. How would I do this inside a foreach loop already? - I am doing something silly and its driving me nuts - ["shipmentItems"]=> array(2) { [0]=> array and then the [0] changes to [1]

    example
     $dbh->query("INSERT INTO `shipments_parts` (`orderNumber`,
    `orderItemId`,
    `orderId`,`sku`,`last_updated`) VALUES ('".$roworderNumber."',
    '".$row['shipmentItems'][1]['orderItemId']."','".$roworderId."','".$row['shipmentItems'][1]['sku']."',
    NOW())");
    
    
    and i changed this -
    $dbh->query("INSERT INTO `shipments_parts` (`orderNumber`,
    `orderItemId`,
    `orderId`,`sku`,`last_updated`) VALUES ('".$roworderNumber."',
    '".$row['shipmentItems'][0]['orderItemId']."','".$roworderId."','".$row['shipmentItems'][0]['sku']."',
    NOW())");
    
    
    PHP:
     
    Solved! View solution.
    xbat, Nov 8, 2017 IP
  2. #2
    Hi - you can have nested foreach statements like this

    foreach($jsonfeed as $row){
       $roworderId = $row['orderId'];
    
       foreach($row['shipmentItems'] as $order){
         $dbh->query("INSERT INTO `shipments_parts` (`orderNumber`, `orderItemId`, `orderId`,`sku`,`last_updated`) VALUES ('{$roworderNumber}', '{$order['orderItemId']}', '{$roworderId}', '{$order['sku']}', NOW())");
       }
    }
    PHP:
     
    sarahk, Nov 8, 2017 IP
  3. xbat

    xbat Well-Known Member

    Messages:
    326
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    105
    #3
    I am getting invalid arguments. i am still trying other things

    Update I think i found the other part. YAY!!

    I added in (array) to

    foreach((array)$row['shipmentItems'] as $order){
    PHP:
     
    Last edited: Nov 8, 2017
    xbat, Nov 8, 2017 IP
  4. xbat

    xbat Well-Known Member

    Messages:
    326
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    105
    #4
    Ahh thank you.. That was it haha I did try that other part before but then I used the word nested in google and I found the (array) thingy right away added it in. thank you very much for your help.
     
    xbat, Nov 8, 2017 IP
    sarahk likes this.