Skip to content
Advertisement

Create a wordpress update query with an associative array done by a for or foreach loop

I want to create an associative array by a loop to add it in a update. The problem i have is that i dont know how to go through each element of the 2 arrays for creating an associative array to put in the update query.

You can see down here i put the array inside another array in the update query but its wrong.

I have the following as an example:

$table = 'name';
$data = [$_POST['eleicons'], $_POST['elepro'], $_POST['elefont'], $_POST['eleanimations']];
$names = ['eleicons', 'elepro', 'elefont', 'eleanimations'];
$counter = 0;
update($table,
array(
foreach($name as $one => $dat){
$one => $dat[$counter],
$counter++;
}),
array('id' => 0));

The array is associative as i said. The update function should look like that:

update($table,
array(
$name[0] => $data[0],
$name[1] => $data[1],
$name[2] => $data[2],
$name[3] => $data[3],
),
array('id' => 0));

But i would like to do that way:

update($table,
$array_associative,
array('id' => 0));

Advertisement

Answer

You can create an associative array from your $names and $data like this:

$count = sizeof($names);    // Get the number of elements in the arrays
// for each element, add the name as the key and the data as the value:
for($i=0; $i<$count; $i++)
    $associative_array[$names[$i]] = $data[$i];

That will create an array like this:

Array
(
    [eleicons] => icons data
    [elepro] => pro data
    [elefont] => font data
    [eleanimations] => animations data
)

You can see the output here (using dummy data of course): https://sandbox.onlinephpfunctions.com/code/68c5f0a92b33625c437e4c5b9ef17c6f9b2ec4bb

Alternatively, as you are using the $_POST, you could create your array this:

foreach($names as $key)
    $associative_array[$key] = $_POST[$key];

The whole code would then be:

$table = 'name';
$names = array('eleicons', 'elepro', 'elefont', 'eleanimations');    
$associative_array = array();

foreach($names as $key)
    $associative_array[$key] = $_POST[$key];

update($table,
       $associative_array,
       array('id' => 0));

IMPORTANT NOTE:

You are using table and update in your code, so if you are adding this into a database, you should sanitize any user-provided data before adding it to you DB, otherwise you are wide open to SQL injection.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement