Domanda

Sto scrivendo una funzione che aggiunge un numero ID a un array e mette la matrice nel usermeta . $_GET['auction'] è il post_id.

Di seguito è la funzione:

$reminders = get_user_meta( $current_user->ID, "reminders" );
print_r( $reminders );
if( in_array( $_GET['auction'], $reminders ) ) {
    echo "Failed: Auction already in list";
} else {
    array_push( $reminders, intval( $_GET['auction'] ) );
    if ( update_user_meta( $current_user->ID, "reminders", $reminders ) ) {
        echo "Success";
    } else {
        echo "Failed: Could not update user meta";
    }
}
print_r( $reminders );

Ecco l'uscita dopo l'aggiunta di una vendita all'asta:

Array ( ) 
Success
Array ( [0] => 7 ) 

Ecco l'uscita dopo l'aggiunta di due aste:

Array ( [0] => Array ( [0] => 7 ) ) 
Success
Array ( [0] => Array ( [0] => 7 ) [1] => 73 )

E qui è l'uscita dopo aver aggiunto tre aste:

Array ( [0] => Array ( [0] => Array ( [0] => 7 ) [1] => 73 ) ) 
Success
Array ( [0] => Array ( [0] => Array ( [0] => 7 ) [1] => 73 ) [1] => 0 )

Si noti che l'aggiunta di un nuovo elemento alla matrice utilizzando array_push funziona bene. Ma quando la matrice è memorizzato nel usermeta poi recuperate nuovamente, l'ultimo elemento della matrice è stata messa in un array propria, creando un array infinitamente dimensionale. Preferirei mantenere questa matrice unidimensionale.

C'è un modo posso correre update_user_meta e get_user_meta senza modificare la struttura del mio array?

È stato utile?

Soluzione

Non ho usato la funzione per parecchio tempo, ma credo che il problema è che si sta spingendo un array in un array. Quindi, controllo se intval($_GET['auction']) è un array:

echo '<pre>';
print_r(intval($_GET['auction']));
echo '</pre>';

Modifica # 1: È forse necessario per ottenere il valore da tale matrice e poi array_push esso. Così forse qualcosa di simile array_push( $reminders, $_GET['auction'][0]) ); - se si sta solo aggiungendo un singolo valore. Si potrebbe anche fare qualcosa di simile $reminders[] = $_GET['auction'][0]; per aggiungerlo alla fine dell'array.

Modifica # 2: Da uno sguardo al file core: sì. update_user_meta() è solo un alias di update_metadata() che prende il ID + il valore e lo mette nel database, come e array.

// From /wp-includes/meta.php ~ line 135
$where = array( $column => $object_id, 'meta_key' => $meta_key );

if ( !empty( $prev_value ) ) {
    $prev_value = maybe_serialize($prev_value);
    $where['meta_value'] = $prev_value;
}

Altri suggerimenti

Ho avuto lo stesso problema. L'aggiunta di "true" a "get_user_meta" lavorato per me. Ad esempio:

da:

$reminders = get_user_meta($current_user->ID,"reminders");

A:

$reminders = get_user_meta($current_user->ID,"reminders",true);

Ha avuto lo stesso problema e risolto con questo po ', che mette tutti i nuovi valori in un singolo array salvato i dati utente meta:

//Where $access_key is the next (added) value

$get_access_keys_from_wp = get_user_meta($user_id,'wsm_capability');
$current_access_keys = $get_access_keys_from_wp[0];
$new_access_keys = array();
$new_access_keys[]=$access_key;

foreach($current_access_keys as $key => $value){
    $new_access_keys[]=$value;
}
delete_user_meta( $user_id, 'wsm_capability');//Clear out the meta data...
update_user_meta( $user_id, 'wsm_capability', $new_access_keys);

Array prima di Save / aggiornamento per meta chiave (da get_user_meta):

Array
(
    [0] => access_9
)

risultante Array (dopo meta aggiornamento) l'aggiunta di valore 'access_5':

Array
(
    [0] => access_5
    [1] => access_9
)

Se è necessario il nuovo valore da aggiungere alla fine della matrice, fare questo, invece:

//Where $access_key is the next (added) value    
$get_access_keys_from_wp = get_user_meta($user_id,'wsm_capability');
$current_access_keys = $get_access_keys_from_wp[0];
$new_access_keys = array();

foreach($current_access_keys as $key => $value){
    $new_access_keys[]=$value;
}
$new_access_keys[]=$access_key;

Poi aggiornare la meta ...

Bryan

Sembrava che il problema era con la serializzazione / deserializzazione, l'array, quindi ho solo riscritto la funzione di essere una virgola sperated stringa:

        $reminders = get_user_meta($current_user->ID,"reminders",TRUE);
        if(is_int(strpos($reminders,$_GET['auction']))) {
            echo "Failed: Auction already in list";
        } else {
            $reminders .= ",".intval($_GET['auction']);
            if(substr($reminders,0,1) == ",") { //Remove leading comma if it exists
                $reminders = substr($reminders,1,strlen($reminders)-1);
            }
            if(update_user_meta($current_user->ID,"reminders",$reminders)) {
                echo "Success";
            } else {
                echo "Failed: Could not update user meta";
            }
        }

La risposta di Shaun era corretta, ma mi sento bisogno di maggiori chiarimenti. Si può mettere in un array in una voce utente meta, ma quando lo si recupera hai ancora bisogno di recuperare con l'unico insieme argomento di vero o altrimenti si ottiene una matrice di un indietro array. Ecco il mio codice:

$past_orders = get_user_meta($order_userID, 'qr-replacement-orders',true);

//see if this new order has already been processed
if(in_array($_GET["oid"],$past_orders))
{
     echo '<p>This order has already been processed.</p>';
    //debug
    //var_dump($past_orders);   
}
else
{
      //add the order number to the array of past orders and store it
     //if list is empty, initialize it to empty array
     if($past_orders == '')
     {
        $past_orders = array();
     }
     //add the new order to the list
    array_push($past_orders, $_GET["oid"]);

    //add the new list to the DB
    update_user_meta($order_userID, 'qr-replacement-orders',$past_orders);

    echo '<p>Your card has been purchased and will be sent to you in the mail.  Thanks!</p>';                       

    //debug: confirm it worked
    //$past_orders = get_user_meta($order_userID, 'qr-replacement-orders',true);
    //var_dump($past_orders);   
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a wordpress.stackexchange
scroll top