gpt4 book ai didi

php - 在php中合并两个索引数组

转载 作者:行者123 更新时间:2023-12-04 20:16:28 25 4
gpt4 key购买 nike

我有两个由 2 个循环创建的索引数组:

$问题

Array ( 
[10] => Yes
[11] => No
[12] => Yes
[13] => No
[14] => Yes
[15] => No
)

$评论

Array ( 
[10] => comment
[11] => comment
[12] => comment
[13] => comment
[14] => comment
[15] => comment
)

如何将它们结合起来,以便得到以下结果并保留索引:

Array ( 
[10] => Yes, comment
[11] => No, comment
[12] => Yes, comment
[13] => No, comment
[14] => Yes, comment
[15] => No, comment
)

查看 array_merge 但如果键相同则追加。

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

查看 array_combine 但是:

Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

我确定我需要第三个循环来“组合”它们,但我该怎么做呢?

最佳答案

这应该会为您提供几个选项。它做出逻辑假设 $questions 和 $comments 之间的键是同步的,并处理是否有一些奇怪的键。

<?php
$questions = array(
'10' => 'Yes',
'11' => 'No',
'12' => 'Yes',
'13' => 'No',
'14' => 'Yes',
'15' => 'No',
'16' => 'No'
);
$comments = array(
'10' => 'comment 10',
'11' => 'comment 11',
'12' => 'comment 12',
'13' => 'comment 13',
'14' => 'comment 14',
'15' => 'comment 15',
'17' => 'comment 17'
);

$combinedAsArray = array();
$combinedAsString = array();

foreach ($questions as $key => $value){

if (array_key_exists($key, $comments)){
$combinedAsArray[$key] = array($value, $comments[$key]);
$combinedAsString[$key] = "$value, {$comments[$key]}";
}else{
$combinedAsArray[$key] = array($value, null);
$combinedAsString[$key] = "$value, ";
}
}

foreach ($comments as $key => $value){
if (! array_key_exists($key, $questions)){
$combinedAsArray[$key] = array(null, $value);
$combinedAsString[$key] = " , $value";
}
}

print_r($combinedAsArray);
print_r($combinedAsString);

关于php - 在php中合并两个索引数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15686098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com