Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.7k views
in Technique[技术] by (71.8m points)

How to merge two arrays based on their index php?

I need to merge 2 arrays and i have found lot of examples here on stackoverflow, but nothing has worked for me, in my case, so i explain my case:

Arrays (can be one, two, or three, or more...):

Array ( [0] => name-file_icon_001_00.png- 
        [1] => name-file_icon_002_00.png-
        [2] => name-file_icon_003_00.png- )
Array ( [0] => rel
        [1] => rel
        [2] => rel )

Or can be two:

Array ( [0] => name-file_icon_001_00.png- 
        [1] => name-file_icon_002_00.png- )
Array ( [0] => rel
        [1] => rel )

Or one:

Array ( [0] => name-file_icon_001_00.png- ) 
Array ( [0] => rel )

Need to insert the relative value "[0] => rel" with "[0] => name-file_icon_001_00.png-"

Expected result (merged):

Array ( [0] => name-file_icon_001_00.png-rel
        [1] => name-file_icon_002_00.png-rel
        [2] => name-file_icon_003_00.png-rel )

Reading around the web, seems that not exist a native function for make this. Please, hope in your help :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A simple foreach loop using the index and value parameters will do it in no time

Example

$a1 = ['name-file_icon_001_00.png-',
        'name-file_icon_002_00.png-',
        'name-file_icon_003_00.png-'
        ];
$a2 = ['rel1','rel2','rel3'];

foreach ($a1 as $i => $v){
    $new[] = $v . $a2[$i];
}
print_r($new);

RESULT

Array
(
    [0] => name-file_icon_001_00.png-rel1
    [1] => name-file_icon_002_00.png-rel2
    [2] => name-file_icon_003_00.png-rel3
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...