Array replace recursive()

Jmnote (토론 | 기여)님의 2016년 2월 1일 (월) 13:30 판 (→‎PHP)
array_replace_recursive()

1 PHP

<?php
$a = array('oragne', array(1,2,3), 'banana');
$b = array('pineapple', array(3,4));

print_r( array_replace_recursive($a, $b) );
# Array
# (
#     [0] => pineapple
#     [1] => Array
#         (
#             [0] => 3
#             [1] => 4
#             [2] => 3
#         )
# 
#     [2] => banana
# )

print_r( array_replace_recursive($b, $a) );
# Array
# (
#     [0] => oragne
#     [1] => Array
#         (
#             [0] => 1
#             [1] => 2
#             [2] => 3
#         )
# 
#     [2] => banana
# )

2 Ruby

def array_replace_recursive(base, replacements)
	base = Marshal.load(Marshal.dump(base))
	replacements.each_with_index do | v, i |
		if( v.kind_of?(Array) )
			base[i] = array_replace_recursive(base[i], v)
		else 
			base[i] = v
		end
	end
	return base
	#return replacements + base.drop(replacements.size)
end

a = ["orange", [1,2,3], "banana"]
b = ["pineapple", [3,4]]

puts array_replace_recursive(a, b)
# pineapple
# 3
# 4
# 3
# banana

puts array_replace_recursive(b, a)
# orange
# 1
# 2
# 3
# banana

3 같이 보기

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}