2017-03-27 58 views
1

如果我使用字符串作爲$鍵,我的代碼可以工作,但如果我使用$ hasorhasnotentered,它會返回「數組」。我如何使用$ Key的變量?如何使用變量作爲密鑰

<?php 
    $user_id = $current_user->ID; 
    $key = $hasorhasnotentered; 
    $single = true; 
    $user_last = get_user_meta($user_id, $key, $single); 
    echo '<p>The '. $key . ' value for user id ' . $user_id . ' is: ' . $user_last . '</p>'; 
?> 

的變量是由下面的表單的用戶交互定義的形式爲代碼

<form method="post" id="adduser" action="/my-likes-list/"> 

<input type="text" name="<?php echo $hasorhasnotentered;?>" id="<?php echo $hasorhasnotentered;?>" value="<?php echo $yesentered; ?>"/> 

<p class="form-submit"> 
     <input name="updateuser" type="submit" id="updateuser" class="submit button" value="update-user" onclick='enterdnew()'/> 
    <?php wp_nonce_field('update-user') ?> 
    <input name="action" type="hidden" id="action" value="Update" /> 
</p> 
</form> 

回答

0

可以使用,就像你做了一個變量。只是變量需要包含一個字符串。顯然,你的$hasorhasnotentered包含。這就解釋了爲什麼它會返回一個數組,因爲如果$ key留空get_user_meta返回一個數組中的所有元數據。請參閱文檔:https://codex.wordpress.org/Function_Reference/get_user_meta

$key (string) (optional) The meta_key in the wp_usermeta table for the meta_value to be returned. If left empty, will return all user_meta fields for the given user. Default: (empty string)

編輯: 在上面的表格代碼,相信你想要的:

<input type="text" name="hasorhasnotentered" id="hasorhasnotentered" value="<?php echo $hasorhasnotentered; ?>"/>

然後,負載,該元素的值將被設置無論$ hasorhasnotentered是。用戶將$ hasorhasnotentered設置爲它們在元素中鍵入的任何文本。

然後,在提交時,$ hasorhasnotentered將是輸入字段的文本。我不得不承認,我可能並不瞭解你的代碼的意圖。

+0

當我使用var_dump時,我得到「空」,但這不是真的,因爲當我使用字符串而不是變量時,我得到正確的結果。 – johnnyr209

+0

檢查您的代碼,確定您設置$ hasorhasnotentered的值的位置。我向你保證它沒有被正確設置。如果你在你定義的代碼中顯示代碼,或許我們可以幫助你弄清楚爲什麼它沒有被設置爲你期望的值。 – vlasits

+0

其通過用戶交互的形式定義 – johnnyr209

0

你的代碼看起來不錯,但我希望你的$ hasorhasnotentered變量不是未定義的。如果它的價值來自用戶輸入檢查定義之前,你使用它!