将数组值与另一个数组合并

时间:2016-01-15 08:02:29

标签: php arrays foreach

我有2个阵列:

var c;
c = {
  a: "abcdefghijklmnopqrstuvwxyz",
  b: "abcdefghijklmnopqrstuvwxyz",
  c: "abcdefghijklmnopqrstuvwxyz",
  d: "abcdefghijklmnopqrstuvwxyz",
  e: "abcdefghijklmnopqrstuvwxyz",
  f: "abcdefghijklmnopqrstuvwxyz",
  g: "abcdefghijklmnopqrstuvwxyz",
  h: "abcdefghijklmnopqrstuvwxyz",
  i: "abcdefghijklmnopqrstuvwxyz",
  j: "abcdefghijklmnopqrstuvwxyz",
  k: "abcdefghijklmnopqrstuvwxyz",
  l: "abcdefghijklmnopqrstuvwxyz"
}
console.log(c)
console.log(c.m)
c.m = "abcdefghijklmnopqrstuvwxyz"

我希望合并它们以使用foreach获得以下结果:

$fields = array('field1'=>'INT', 'field2'=>'STR', 'field3'=>'INT');
$values = array('pour field1', 'pour field2', 'pour field3');

因此结果将显示为:

foreach($fields as $setK=>$setV){

        echo 'k '.$setK.' v '.$setV.'<br />';

        echo "Items are $setK 'THE VALUES OF VALUES ARRAY HERE' $setV";

    }

谢谢你

2 个答案:

答案 0 :(得分:1)

foreach (array_keys($fields) as $i => $key) {
    echo 'Items are ', $key, ' ', $values[$i], ' ', $fields[$key];
}

您需要保持键偏移的运行整数计数才能从$values获得相同的索引;我们通过循环键并将其索引用作$i来实现此目的。

答案 1 :(得分:1)

以下是array_map的解决方案:

array_map(function($key, $f, $v){
    echo "Items are ". $key. " ". $v." " . $f ."<br>";
}, array_keys($fields), $fields, $values);