dongri1989 2016-11-02 04:48
浏览 44
已采纳

如何通过数组值引用嵌套类值

I think the best way to explain my question is to give an example. Say I have the following object.

$data=new stdClass;
$data->test=new stdClass;
$data->test->test2=6;
$data->s=array('b',6,7);

I want to know how I can read or change any value in the object given the key value as an array.

I know the below won't work:

function doSomething($inputArray1,$inputArray2) {
    $data[  $inputArray1   ]; //6
    $data[  $inputArray2   ]=4; //was array('b',6,7);
}

//someone else provided
doSomething( array('test','test2')  , array('s')  );

Changed to make clear that I do not know the values of the array personally so using $data->test->test2; to get the 6 like I normally would won't work. Also do not know the array length.

  • 写回答

2条回答 默认 最新

  • dongma1666 2016-11-02 11:44
    关注

    Figured it out:

    $parts=array('test','test2');
    
    
    $ref=&$data;
    foreach($parts as $part) {
        if (is_array($ref)) {
            $ref=&$ref[$part]; //refrence next level if array
        } else {
            $ref=&$ref->$part; //refrence next level if object
        }
    }
    echo $ref; //show value refrenced by array
    $ref=4; //change value refrenced by array(surprised this works instead of making $ref=4 and breaking the refrence)
    unset($ref); //get rid of refrence to prevent accidental setting.  Thanks @mpyw
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测