doutao6380 2017-04-06 14:07
浏览 46
已采纳

将R向量传递给PHP数组

I am trying to pass the numeric vector from R to an array in PHP.

index.php:

<?php
    $n = 3;
    $out = array();

    exec("Rscript script.R $n", $out);

    $length = count($out);
    echo "length = ".$length."<br>";

    for($i = 0; $i < $length; $i++)
        echo "out[$i] = ".$out[$i]
?>

script.R:

#!/usr/bin/env Rscript

i <- as.numeric(commandArgs(TRUE))
print(i:10)

Output:

length = 1  
out[0] = [1] 3 4 5 6 7 8 9 10

As you can see from the above output, PHP is storing a R vector as a single element of an array. How do I store the individual elements of a R vector in PHP array?

  • 写回答

1条回答 默认 最新

  • dongxianchu3541 2017-04-07 05:47
    关注

    I found the solution at php-r.

    I changed my index.php as:

    exec("Rscript my_script.R $n", $out);
    
    $length = count($out);
    for ($i = 0; $i < $length; $i++)
    foreach (explode("
    ", $out[$i]) as $row) {
        If (strpos($row, ']') !== false)
            $numbersAsStr = substr($row, strpos($row, ']') + 1); 
        else
            $numbersAsStr = $row;
        foreach (explode(' ', $numbersAsStr) as $potentialNumber)
            if ($potentialNumber !== '')
                array_push($result, 0 + $potentialNumber);
    }
    var_dump($result);
    

    Output:

    array(8) { [0]=> int(3) [1]=> int(4) [2]=> int(5) [3]=> int(6) [4]=> int(7) [5]=> int(8) [6]=> int(9) [7]=> int(10) } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?