以下のようにforeach文を回して配列を作るとき、値に何も入らないまま配列ができてしまうことがあります。
foreach ($posts as $post) {
setup_postdata($post);
$post_id = $post->ID;
$post_customfields = get_post_custom($post_id);
$array_post[$post_id] = array(
'hoge1' => $post_customfields['hoge1'][0],
'hoge2' => $post_customfields['hoge2'][0],
'hoge3' => $post_customfields['hoge3'][0]
);
}
foreach($post_ids as $post_id){
echo $array_post[$post_id]['hoge2'];
}
値が入っていないものを参照しようとすると、Undefined indexというエラーが発生します。
空のときにはNULLを代入するよう処理に加えることで、このエラーが出ないようにすることができます。
function undefined_null($array, $key){
$return = isset($array[$key])? $array[$key] : NULL;
return $return;
}
foreach ($posts as $post) {
setup_postdata($post);
$post_id = $post->ID;
$post_customfields = get_post_custom($post_id);
$array_post[$post_id] = array(
'hoge1' => $post_customfields['hoge1'][0],
'hoge2' => undefined_null($post_customfields, "hoge2"),
'hoge3' => $post_customfields['hoge3'][0]
);
}
foreach($post_ids as $post_id){
echo $array_post[$post_id]['hoge2'];
}


