Array foreach loop PHP

后端 未结 2 1250
后悔当初
后悔当初 2021-01-20 16:34

Hello everyone here is my case:

I\'m crawling through the old page with more than 10 000 comments which I\'m trying to import to WordPress.

I\'m using simpl

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-20 17:14

    I am not a wp coder and been years I used it for a demo! You can use key like this, atleast how I would do in php.

        $a = array(
          array(
            'id' => 5698,
            'first_name' => 'Peter',
            'last_name' => 'Griffin',
          ),
          array(
            'id' => 4767,
            'first_name' => 'Ben',
            'last_name' => 'Smith',
          ),
          array(
            'id' => 3809,
            'first_name' => 'Joe',
            'last_name' => 'Doe',
          )
        );
    //Collect array values excrated from foreach
        $Collected_array_result = array();
        foreach($a as $key => $value ) {
            $Collected_array_result[':'.$key] = $value;
        }
       //Create another array from that values 
        print_r($Collected_array_result);
    

    Output

    Array ( [:0] => Array ( [id] => 5698 [first_name] => Peter [last_name] => Griffin ) [:1] => Array ( [id] => 4767 [first_name] => Ben [last_name] => Smith ) [:2] => Array ( [id] => 3809 [first_name] => Joe [last_name] => Doe ) );
    

    And how to put in db

    $stmt = $pdo->prepare("INSERT INTO comments ( " . implode(', ',array_keys($a)) . ") VALUES (" . implode(', ',array_keys($Collected_array_result)) . ")");
    $result = $stmt->execute($Collected_array_result);
    

    Get names from array and create a new array with names:

    $first_name = array_column($a, 'first_name', 'id');
    print_r($first_name);
    

    output

    Array ( [5698] => Peter [4767] => Ben [3809] => Joe );
    

    UPDATE : On @Dharman comment for sql injection and insert data in db using prepared statement, wasnt asked for insert query in question but in case you use that query, please filter values from array or use like following.

    $first_name = array_column($a, 'first_name');
    $first = implode(', ', $first_name);
     echo $first;
    
    $last_names = array_column($a, 'last_name');
    $last = implode(', ', $last_names);
     echo $last;
    
    $id = array_column($a, 'id');
    $iffffd = implode(', ', $id);
     echo $iffffd;
    
    $sql = "INSERT INTO comments (first_name, last_names) VALUES (?,?)";
    $stmt= $pdo->prepare($sql);
    $stmt->execute([$first, $last]);
    

    imploded all values in array and added to query 1 by 1.

提交回复
热议问题