【问题标题】:how to combine two specific arrays keys and values together, in PHP?如何在 PHP 中将两个特定的数组键和值组合在一起?
【发布时间】:2012-06-13 22:59:26
【问题描述】:

我有两个有趣的数组,我试图将它们组合在一起。简单地说:

$firstArr

array(3) {
  [0] => array(2) {
    [0] => string(1) "1"
    [1] => string(16) "test1"
  }
  [1] => array(2) {
    [0] => string(1) "8"
    [1] => string(26) "test2"
  }
  [2] => array(2) {
    [0] => string(1) "9"
    [1] => string(23) "test3"
  }
}


$secondArr

array(3) {
  [0] => string(1) "1"
  [1] => string(1) "2"
  [2] => string(1) "3"
}

我想得到的是这样的东西(不是数组):

$x = 1, 8, 8, 9, 9, 9;
$y = test1, test2, test2, test3, test3, test3;

基本上,第二个数组值决定了第一个数组值的重复次数。

有什么想法吗?

【问题讨论】:

  • 你想在$x$y中存储什么?
  • 如果xy 不是数组,那么它们是什么?

标签: php arrays merge


【解决方案1】:

$firstArr=array(array("1","test1"),array("8","test2"),array("9","test3"));


$secondArr=array("1","2","3");


$x=$y='';
foreach ($secondArr as $k=>$v){
$x.= str_repeat($firstArr[$k][0].',',$v);
$y.= str_repeat($firstArr[$k][1].',',$v);
}

echo rtrim($x,",").";\n";
echo rtrim($y,",").";";

输出:

1,8,8,9,9,9;
测试1,测试2,测试2,测试3,测试3,测试3;

工作演示:

http://codepad.org/yFvWs0Rh

【讨论】:

  • str_repeat() 只需要 2 个参数,3 个给定,但有趣的方法
  • 连接的句号不是逗号,但它仍然坏了,会修复一下
  • 我可以做类似的事情:str_repeat($firstArr[$a][0].',',$a) 我得到string(9) "8,9,9,,,," 和`string(78) "test2,test3,test3,,,,"`,它没有给出所有参数
  • 我也得到了Notice: Undefined offset: 3$x$y 行。看起来数组没有深入:)
  • 成功。连接它如何抱怨3rd offset,现在它没有。你愿意为我解释一下吗?
猜你喜欢
  • 1970-01-01
  • 2011-07-22
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多