Turning a spreadsheet into array and loop and call a function

一曲冷凌霜 提交于 2019-12-13 18:31:44

问题


This is related to generate groups in BuddyPress.

I have a spreadsheet with (in this case) a group name, group description and slug.

I need to grab the information from the file, turn it into an array, then loop through it and call groups_create_group() every time.

I can find that function in bp-groups.php (http://www.nomorepasting.com/getpaste.php?pasteid=35217). It tells me all the parameters you need to fill in.

I'm quite new to this and looking for how I can do this. Do you know how I can grab this information and turn it into an array? An loop it through and call groups_create_group() every time?

If you have any handy links regarding this as well I'll appreciate it.


回答1:


As long as you have the function groups_create_group available (ie. The required file has been included) you should be able to do something like this

<?php

$groups = array();

if (($handle = fopen("groupData.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $group = array('group_id' => 'SOME ID', 'name' => $data[0], 'description' => $data[1], 'slug' => $data[2], 'date_created' => gmdate( "Y-m-d H:i:s" ), 'status' => 'public' );
        $groups[] = $group;
    }   
    fclose($handle);
}

foreach ($groups as $group) {
    groups_create_group($group);
} 

Note, the call to groups_create_group in the pasted code you provided was explicitly calling another method to sanitize the slug before passing it to the function. So you may want to change the assignment to the $group variable to this:

 $group = array('group_id'    => 'SOME ID', 
                'name'        => $data[0], 
                'description' => $data[1], 
                'slug' => groups_check_slug(sanitize_title(esc_attr($data[2]))), 
                'date_created' => gmdate( "Y-m-d H:i:s" ), 
                'status' => 'public' 
 );


来源:https://stackoverflow.com/questions/4547681/turning-a-spreadsheet-into-array-and-loop-and-call-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!