H
H
Historian1112019-05-28 18:43:01
Yii
Historian111, 2019-05-28 18:43:01

Is it possible to sort through such an array in one loop and save it to the database in Yii2?

Fixed a little question and post at the request of people and site administration
Good evening. Sorry for the possibly childish questions, unfortunately there is not much time for your favorite pastime, and in the pauses everything just disappears from your head, because of this there is always a mess in your head.
In general, the essence is this, is it possible to sort it out in one cycle and immediately save the result to the database? And how to do it right? Selected what you need to take from each key of the array. In the next cycle, the keys are identical.
I'm sure the answer is very simple, but I just can't figure it out... Although I used to work calmly with arrays..... Don't kick too hard.
I work in Yii2 and if it's not difficult, show an example of how to implement all this there?

My class
public function tournaments($date, $timestamp){
        $requests = $this->request("//$date/json?_=$timestamp");

//        $result = [];
//        foreach ($requests['sportItem']['tournaments'] as $key => $request){
//            $result['tournament'] .= $request['tournament']['name'];
//            $result['tournament'] .= $request['tournament']['uniqueId'];
//            $result[] = $request['category']['name'];
//            $result[] = $request['category']['id'];
//            $result[] = $request['season']['year'];
//        }

        return $requests['sportItem']['tournaments'];
    }

request, substituting in the link of the part of the site to which I am connecting and parsing is in progress. Forich did it just on a LAN, without a freeworker. In model already configured on the table in a DB. Created
controller
<?php


namespace app\controllers;



use yii\web\Controller;
use app\components\parseTennis;

class TennisController extends Controller
{
        protected $header =заголовки
        ];
        protected $referer = 'сайт';


    public function actionIndex(){
        $tennis = parseTennis::app("https://www.sofascore.com/tennis")
            ->set(CURLOPT_REFERER, $this->referer)
            ->set(CURLOPT_USERAGENT, $this->header);
        $result = $tennis->tournaments(date("Y-m-d"), time('d', 'm', 'Y'));

        return $this->render('index', ['result' => $result]);
    }
}
, perhaps not correctly, where I pass parameters and receive array data.
array
[0] => Array
(
              [tournament] => Array
                  (
                      [name] => Roland Garros, Paris, France
                      [slug] => roland-garros-paris-france
                      [id] => 66712
                      [uniqueId] => 2480
                      [uniqueName] => Roland Garros
                )

            [category] => Array
                          (
                      [name] => ATP
                      [slug] => atp
                      [priority] => 7
                      [id] => 3
                      [flag] => atp
                )

            [season] => Array
                          (
                              [name] => 2019 French Open Men Singles
                              [slug] => 2019-french-open-men-singles
                              [year] => 2019
                              [id] => 20188
                )
      )

etc. Only the first key changes from 0 to 1, and so on, and all values ​​change.
The data I need is from tournament uniqueIdunique Name, from category name, id, from season year
I would be very grateful for any help :)
update
Model
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "tournaments".
 *
 * @property int $id
 * @property string $name
 * @property int $uniqueId
 * @property string $category
 * @property int $categori_id
 * @property int $year
 */
class Tennis extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'tournaments';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['uniqueId', 'categori_id', 'year'], 'integer'],
            [['name'], 'string', 'max' => 255],
            [['category'], 'string', 'max' => 50],
            [['uniqueId'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'uniqueId' => 'Unique ID',
            'category' => 'Category',
            'categori_id' => 'Categori ID',
            'year' => 'Year',
        ];
    }
}

And slightly modified
controller
public function actionIndex(){


        $tennis = parseTennis::app("https://www.sofascore.com/tennis")
            ->set(CURLOPT_REFERER, $this->referer)
            ->set(CURLOPT_USERAGENT, $this->header);
        $results = $tennis->tournaments(date("Y-m-d"), time('d', 'm', 'Y'));

        $tournamentName = [];
        $tournamentUniqueId = [];
        $categoryName = [];
        $categoryId = [];
        $seasonYear = [];
        foreach ($results['sportItem']['tournaments'] as $request){
            $tournamentName[] = $request['tournament']['name'];
            $tournamentUniqueId[] = $request['tournament']['uniqueId'];
            $categoryName[] = $request['category']['name'];
            $categoryId[] = $request['category']['id'];
            $seasonYear[] = $request['season']['year'];
        }

        $model = new Tennis();
        $model->name = $tournamentName;
        $model->uniqueId = $tournamentUniqueId;
        $model->category = $categoryName;
        $model->categori_id = $categoryId;
        $model->year = $seasonYear;

        return $this->render('index', [
                            'model' => $model,
        ]);
    }

The only thing I do not understand is how to transfer all this to the database :(

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
Andrew, 2019-05-28
@Historian111

Spherical code in vacuum:

spoiler
$data =   array (
        [1] => array(
            'title' => "xxxxx",
            'content' => "xxxxx",
            'category' => "xxxxx",
        ), 
        [2] => array(
            'title' => "xxxxx",
            'content' => "xxxxx",
            'category' => "xxxxx",
        ), 
        [3] => array(
            'title' => "xxxxx",
            'content' => "xxxxx",
            'category' => "xxxxx",
        ), 
     );

if(is_array($data)){
    foreach($data as $row){
        $sql = "INSERT INTO `table`( `title`, `content`, `category`) values";

        $title = mysql_real_escape_string( $row['title'] );
        $content = mysql_real_escape_string( $row['content'] );
        $category = mysql_real_escape_string( $row['category'] );

        $sql .= "('" . $title . "','" . $content, "','" $category "')";
        mysql_query($sql) or exit(mysql_error()); 
    }
}

Use MySQLi instead of MySQL
In general, the answer is easily googled:
https://stackoverflow.com/questions/39818418/using...
https://stackoverflow.com/questions/15013211/how-t...
Because the structure nested does not change much:
spoiler
if(is_array($data)){
    foreach($data as $row){
        $tournamentName = $row['tournament']['name'];
        $tournamentSlug = $row['tournament'][];
        $tournamentId = $row['tournament'][];
        $tournamentUniqueId = $row['tournament'][];
        $tournamentUniqueName = $row['tournament'][];

        $categoryName = $row['category']['name'];
        $categorySlug = $row['category']['slug'];
        $categoryPriority = $row['category']['priority'];
        $categoryId = $row['category']['id'];
        $categoryFlag = $row['category']['flag'];
    }
}

But there is a nuance here, further work with the database depends on how you are going to store this data.
Those. it is not clear how the data models in which you want to store this information are described.

C
chelkaz, 2017-06-10
@lemonlimelike

Check for all browsers:

var elem = document.getElementById("myvideo");
if (elem.requestFullscreen) {
  // elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) {
  // elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
  // elem.webkitRequestFullscreen();
}

Here are the conditions for checking the full window:
https://developer.mozilla.org/en-US/docs/Web/API/W...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question