Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

php - Laravel How to loop through arrays and get values by key

In my laravel-application I have two arrays, one called "headers" and one called "rows" and I only want the data from the "row" array which is based on the key from the "headers" array.

So here are my arrays:

  "rows" => array:2 [
     0 => array:6 [
        "Company name" => "Universal"
        "Address" => "Some address"
        "Zipcode" => 12122
        "City" => "Some city"
        "Phonenumber" => 12345678
        "Email" => "[email protected]"
     ],
     1 => array:6 [
        "Company name" => "Warner Bros."
        "Address" => "another address"
        "Zipcode" => 12122
        "City" => "city abc"
        "Phonenumber" => 12345678
        "Email" => "[email protected]"
     ]

  ],
  "headers" => array:4 [
     0 => array:2 [
       "name" => "Company name"
       "data" => array:1 [
          "value" => "company_name"
       ]
     ],
     1 => array:2 [
      "name" => "Adresse"
      "data" => array:1 [
         "value" => "address"
      ]
    ]
  ]

So far so good, now I only want the data from the "rows"-array which is selected from the "headers" array, so that I can display them like this in my frontend:

Company name    |    Address
----------------------------------
Universal       |    Some address
Warner Bros.    |    Another address

So, how can I store them in the database? My Model structure is this:

Entry::create([
    'company_name' => request()->company_name ?? null,
    'address' => request()->address ?? null,
    'zipcode' => request()->zipcode ?? null,
    'city' => request()->city ?? null,
    'number' => request()->number ?? null,
    'email' => request()->email ?? null
]);

Thanks in advance...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Hi friend loop through the companies array first, and dynamically create a array and pass it to the model as below

$data = $request->rows;
$columns = $request->headers;

foreach($data as $item){

  $array_of_items = [] 
  
  foreach($columns as $column){
     
     $column_name = $column['name']; //should return "Company Name"      

     if($item[$column_name]){ // means has the value
       $column_code = $column['data']['value'] //should return "company_name" in first loop and so on, if not cannot carry on
       $array_of_items[$column_code] = $item[$column_name];
     }
     
  }

  if(!empty($array_of_items)){
     Entry::create($array_of_items);
  }


}

If anything in doubt feel free to comment, thank you have a nice day.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...