Cómo insertar tanto el valor como la clave en la matriz


Echa un vistazo a este código:

$GET = array();    
$key = 'one=1';
$rule = explode('=', $key);
/* array_push($GET, $rule[0] => $rule[1]); */

Estoy buscando algo como esto para que:

print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */

Hay una función para hacer esto? (porque array_push no funcionará de esta manera)

 270
Author: Chris Forrence, 2010-01-23

16 answers

No, no hay array_push() equivalente para matrices asociativas porque no hay manera de determinar la siguiente clave.

Tendrás Que usar

$arrayname[indexname] = $value;
 591
Author: Pekka 웃,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-23 00:45:43

Al empujar un valor dentro de un array se crea automáticamente una clave numérica para él.

Al agregar un par clave-valor a una matriz, ya tiene la clave, no necesita que se cree una para usted. Empujar una clave en una matriz no tiene sentido. Solo puede establecer el valor de la clave específica en la matriz.

// no key
array_push($array, $value);
// same as:
$array[] = $value;

// key already known
$array[$key] = $value;
 63
Author: deceze,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-28 03:52:26

Puede usar el operador union (+) para combinar matrices y mantener las claves de la matriz agregada. Por ejemplo:

<?php

$arr1 = array('foo' => 'bar');
$arr2 = array('baz' => 'bof');
$arr3 = $arr1 + $arr2;

print_r($arr3);

// prints:
// array(
//   'foo' => 'bar',
//   'baz' => 'bof',
// );

Así que podrías hacer $_GET += array('one' => 1);.

Hay más información sobre el uso del operador de la unión vs array_merge en la documentación en http://php.net/manual/en/function.array-merge.php .

 48
Author: Charlie Schliesser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-12 13:51:06

Exactamente lo que Pekka dijo...

Alternativamente, probablemente puede usar array_merge de esta manera si lo desea:

array_merge($_GET, array($rule[0] => $rule[1]));

Pero preferiría el método de Pekka probablemente ya que es mucho más simple.

 16
Author: jeffff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-23 00:48:50

Me gustaría añadir mi respuesta a la tabla y aquí está:

//connect to db ...etc
$result_product = /*your mysql query here*/ 
$array_product = array(); 
$i = 0;

foreach ($result_product as $row_product)
{
    $array_product [$i]["id"]= $row_product->id;
    $array_product [$i]["name"]= $row_product->name;
    $i++;
}

//you can encode the array to json if you want to send it to an ajax call
$json_product =  json_encode($array_product);
echo($json_product);

Espero que esto ayude a alguien

 14
Author: Nassim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-05 10:24:06

Estaba buscando lo mismo y me di cuenta de que, una vez más, mi pensamiento es diferente porque soy de la vieja escuela. Voy todo el camino de vuelta a BASIC y PERL y a veces me olvido de lo fácil que son las cosas en PHP.

Acabo de hacer esta función para tomar todas las configuraciones de la base de datos donde están 3 columnas. setkey, item (key) & value (value) y colóquelos en una matriz llamada settings usando la misma clave/valor sin usar push como arriba.

Bastante fácil & simple realmente


// Get All Settings
$settings=getGlobalSettings();


// Apply User Theme Choice
$theme_choice = $settings['theme'];

.. etc etc etc ....




function getGlobalSettings(){

    $dbc = mysqli_connect(wds_db_host, wds_db_user, wds_db_pass) or die("MySQL Error: " . mysqli_error());
    mysqli_select_db($dbc, wds_db_name) or die("MySQL Error: " . mysqli_error());
    $MySQL = "SELECT * FROM systemSettings";
    $result = mysqli_query($dbc, $MySQL);
    while($row = mysqli_fetch_array($result)) 
        {
        $settings[$row['item']] = $row['value'];   // NO NEED FOR PUSH
        }
    mysqli_close($dbc);
return $settings;
}


Así como los otros posts explican... En php no hay necesidad de "EMPUJAR" una matriz cuando se está utilizando

Clave = > Valor

Y... Tampoco es necesario definir primero el array.

Array array=array ();

No es necesario definir o empujar. Simplemente asigne array array [key key] = value value; es automáticamente un push y una declaración al mismo tiempo.

Debo agregar que por razones de seguridad, (P)oor (H)elpless (P)rotection, significa Programación para Maniquíes, quiero decir PHP.... hehehe sugiero que solo uses este concepto para lo que pretendía. Cualquier otro método podría ser un riesgo para la seguridad. Ahí, hice mi descargo de responsabilidad!

 6
Author: Cory Cullers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-28 04:10:45

Esta es la solución que puede ser útil para u

Class Form {
# Declare the input as property
private $Input = [];

# Then push the array to it
public function addTextField($class,$id){
    $this->Input ['type'][] = 'text';
    $this->Input ['class'][] = $class;
    $this->Input ['id'][] = $id;
}

}

$form = new Form();
$form->addTextField('myclass1','myid1');
$form->addTextField('myclass2','myid2');
$form->addTextField('myclass3','myid3');

Cuando lo vuelcas. El resultado como este

array (size=3)
  'type' => 
    array (size=3)
      0 => string 'text' (length=4)
      1 => string 'text' (length=4)
      2 => string 'text' (length=4)
  'class' => 
    array (size=3)
      0 => string 'myclass1' (length=8)
      1 => string 'myclass2' (length=8)
      2 => string 'myclass3' (length=8)
  'id' => 
    array (size=3)
      0 => string 'myid1' (length=5)
      1 => string 'myid2' (length=5)
      2 => string 'myid3' (length=5)
 5
Author: Faris Rayhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-06 15:49:00

Un poco raro, pero esto funcionó para mí

    $array1 = array("Post Slider", "Post Slider Wide", "Post Slider");
    $array2 = array("Tools Sliders", "Tools Sliders", "modules-test");
    $array3 = array();

    $count = count($array1);

    for($x = 0; $x < $count; $x++){
       $array3[$array1[$x].$x] = $array2[$x];
    }

    foreach($array3 as $key => $value){
        $output_key = substr($key, 0, -1);
        $output_value = $value;
        echo $output_key.": ".$output_value."<br>";
    }
 3
Author: Bjorn Lottering,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-02 16:06:47

Un poco tarde, pero si no le importa una matriz anidada, podría tomar este enfoque:

$main_array = array(); //Your array that you want to push the value into
$value = 10; //The value you want to push into $main_array
array_push($main_array, array('Key' => $value));

Para aclarar, si la salida json_encode($main_array) que se parecen a [{"Clave":"10"}]

 2
Author: Pontus B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-26 21:00:12
 $arr = array("key1"=>"value1", "key2"=>"value");
    print_r($arr);

/ / imprime array ['key1' = > "value1",'key2' =>"value2"]

 2
Author: sneha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-14 09:25:56

Me pregunto por qué el método más simple aún no se ha publicado:

$arr = ['company' => 'Apple', 'product' => 'iPhone'];
$arr += ['version' => 8];

Es lo mismo que fusionar dos matrices con array_merge.

 0
Author: AlexioVay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-21 13:25:21

Hola tuve el mismo problema me parece que esta solución debe utilizar dos matrices y luego combinarlos ambos

 <?php

$fname=array("Peter","Ben","Joe");

$age=array("35","37","43");

$c=array_combine($fname,$age);

print_r($c);

?>

Referencia : w3schools

 0
Author: fantome195,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-20 21:42:16

El camino simple:

$GET = array();    
$key = 'one=1';
parse_str($key, $GET);

Http://php.net/manual/de/function.parse-str.php

 0
Author: eSlider,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-25 09:09:32

Array_push(GET GET, GET GET ['one'] = 1);

Funciona para mí

 0
Author: aaa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-17 12:40:25

Ejemplo array_merge()....

$array1 = array("color" => "red", 2, 4); $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4); $result = array_merge($array1, $array2); print_r($result);

Array([color] => verde,[0] => 2,[1] => 4,[2] => a, [3] => b, [forma] => trapezoide,[4] => 4,)

 0
Author: illeas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-28 17:58:47
array_push($arr, ['key1' => $value1, 'key2' => value2]);

Esto funciona muy bien. crea la clave con su valor en el array

 -1
Author: Mesh Manuel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-16 11:50:26