douzhan1238 2017-06-19 20:18
浏览 23
已采纳

PHP foreach /在多维数组的一部分上使用键+值对

I am trying to access data from a multidimensional array. Array $o contains arrays of with the key: product_id. The child array 'data' contains key => value pairs (or at least I think it does). The problems is that when I try to access the data later on: nothing is working.

Question: How can I access this data as expected in a key => value pair method that works (like foreach($o[$_product_id]['data'] as $_attr => $_value))

Original data

$_product_id=1;
$h = array('header1','header2','header3');
$line= array(1,2,3);
$o[$_product_id]['data'] = array_combine($h,array_map('trim', $line));

I var_dumped $o[$_product_id]['data'] and I can see the data is there

$data =
array (
  'header1' => 1,
  'header2' => 2,
  'header3' => 3,
);

Help appreciated

=======================

Loading data original method

$o[$_product_id]['data'] = array_combine($h,array_map('trim', $line));

Loading data alternative method

foreach ($h as $_atr) {
  $o[$_product_id]['data'][$_atr] = trim(array_shift($line));
}

Accessing data: not working as expected

foreach($o[$_product_id]['data'] as $_attr => $_value)
  echo $_attr;
  echo $_value;
  • 写回答

1条回答 默认 最新

  • donglun1020 2017-06-19 20:34
    关注

    Okay, your problem is that your code:

    foreach($o[$_product_id]['data'] as $_attr => $_value)
      echo $_attr;
      echo $_value;
    

    is equivalent to:

    foreach($o[$_product_id]['data'] as $_attr => $_value) {
      echo $_attr;
    }
    echo $_value;
    

    See? You iterate over array, but output only keys, and last value after the end.

    And yes, this is the standard behaviour of a foreach without {} - after foreach definition only one line runs in a loop. All other lines are considered out of the loop. Yep, that's not like in python).

    So the fix is simple - add {}:

    foreach($o[$_product_id]['data'] as $_attr => $_value) {
      echo $_attr;
      echo $_value;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?