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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘