matometaru
3/8/2018 - 11:34 AM

配列の任意の指定位置に差し込み

<?php
	$args = array(
		'post_type'  => 'event',
		'meta_key'   => 'home_attend',
		'meta_value' => true,
		'posts_per_page' => -1,
	);
	$the_query = new WP_Query( $args );
	if ( $the_query->have_posts() ) :
?>
<?php
$a = array(
	'0'=>array('a'=>'orange', 'b'=>'banana'),
	'1'=>array('a'=>'orange', 'b'=>'banana'),
	'2'=>array('a'=>'orange', 'b'=>'banana'),
);
$b = array(
	'pr'=>array('a'=>'test', 'b'=>'test'),
);
echo '<pre>';
print_r($a);
echo '</pre>';
function array_insert($origin,$position,$insert){
	if(!is_array($origin) || !is_array($insert)){
		return false;
	}
	$origin_keys=array_keys($origin);
	$origin_values=array_values($origin);
	$insert_keys=array_keys($insert);
	$insert_values=array_values($insert);
	array_splice($origin_keys,$position,0,$insert_keys);
	array_splice($origin_values,$position,0,$insert_values);
	return array_combine($origin_keys,$origin_values);
}
$c = array_insert($a,1,$b);
echo '<pre>';
print_r($c);
echo '</pre>';
?>	

出力
Array
(
    [0] => Array
        (
            [a] => orange
            [b] => banana
        )

    [1] => Array
        (
            [a] => orange
            [b] => banana
        )

    [2] => Array
        (
            [a] => orange
            [b] => banana
        )

)
Array
(
    [0] => Array
        (
            [a] => orange
            [b] => banana
        )

    [pr] => Array
        (
            [a] => test
            [b] => test
        )

    [1] => Array
        (
            [a] => orange
            [b] => banana
        )

    [2] => Array
        (
            [a] => orange
            [b] => banana
        )

)