php 使用键从 foreach 循环创建数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6398317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:14:21  来源:igfitidea点击:

Create array from foreach loop with key

phparraysforeach

提问by Reg

I couldn't quite find the exact solution that I am looking for.

我无法完全找到我正在寻找的确切解决方案。

I am trying to create an array from a foreach loop that retains the key. Here is the code I have so far but it only keeps the last value in the array:

我正在尝试从保留键的 foreach 循环创建一个数组。这是我到目前为止的代码,但它只保留数组中的最后一个值:

foreach($links as $link) {
  //runs scrape_amazon function for each of the links
  $ret = scrape_amazon($link);

  foreach($ret as $key => $value) {
    //echo $key; 
    //echo $value;
    $final_results[$key] = $value;
  }
}

Could anyone help with a solution to keep all the values and the keys?

任何人都可以帮助解决保留所有值和键的解决方案吗?

Thanks in advance!

提前致谢!

回答by Francois Deschenes

Based on your most recent comment, this should solve your problem:

根据您最近的评论,这应该可以解决您的问题:

$ret = array();

foreach($links as $link) {
  $ret[] = scrape_amazon($link);
}

Each time scrape_amazon()is called, it'll add the array returned to $retmaking it into an array of arrays.

每次scrape_amazon()调用时,它都会添加返回的数组以$ret使其成为数组数组。

回答by Adithya Surampudi

If you need an array of just keys, you need to do this

如果您只需要一组键,则需要执行此操作

$ret_keys = array_keys($ret);

回答by Ben

why did you do that ? it's look like :

你为什么这么做 ?它看起来像:

$final_results = $ret;

回答by Playnox

  // Create an empty array first      
  $final_results = array();
  foreach($links as $link) {
      //runs scrape_amazon function for each of the links
      $ret = scrape_amazon($link);
      $final_results[] = $ret; // DONE :)
  }