简体   繁体   中英

How to build an array from another array in PHP

I'm trying to create a basic export. I have an array of nodes but I'm having trouble conceiving how to use this with my CVS script. I'm very new to PHP. It's the where to place the foreach that I'm having trouble with.

Here is my node code.

foreach ($nodes as $node) {
    print $node->nid;
    print $node->title; 
}

// here is my cvs code.

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

$mydata = array(
    array('data11', 'data12', 'data13'),
    array('data21', 'data22', 'data23'),
    array('data31', 'data32', 'data23'));
outputCSV($csv);

function outputCSV($data) {
    $outstream = fopen("php://output", 'w');
    function __outputCSV(&$vals, $key, $filehandler) {
        fputcsv($filehandler, $vals); // add parameters if you want
    }
    array_walk($data, '__outputCSV', $outstream);
    fclose($outstream);

}

The quick and diry solution would be to force cast the $vals variable to an array, so your function would look like this:

function outputCSV($data) {
    $outstream = fopen("php://output", 'w');
    function __outputCSV(&$vals, $key, $filehandler) {
        if (is_object($vals)) {
            $vals = (array)$vals;
        }
        fputcsv($filehandler, $vals); // add parameters if you want
    }
    array_walk($data, '__outputCSV', $outstream);
    fclose($outstream);
}

This is possible because, and i quote from here , "if an object is converted to an array, the result is an array whose elements are the object's properties."

Another solution is to traverse your $nodes array and create a new one according to the structure that your CSV generation function accepts:

$dataFromNodes = array();
foreach ($nodes as $node) {
   $dataFromNodes[] = array($node->nid, $node->title);
}

Then, call your function using the newly created array:

outputCSV($dataFromNodes);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM