[php] PHP 배열에 값과 키를 모두 넣는 방법

이 코드를 살펴보십시오.

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

나는 이와 같은 것을 찾고있다.

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

이를 수행하는 기능이 있습니까? ( array_push이 방법으로 작동하지 않기 때문에 )



답변

아니, 전혀 없다 array_push()방법은 다음 키를 결정 없기 때문에 연관 배열에 해당.

당신은 사용해야합니다

$arrayname[indexname] = $value;


답변

값을 배열로 푸시 하면 자동으로 숫자 키가 생성됩니다.

키-값 쌍을 배열에 추가 할 때 이미 키가 있으므로 키를 만들 필요가 없습니다. 키를 배열에 넣는 것은 의미가 없습니다. 배열의 특정 키 값만 설정할 수 있습니다.

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

// key already known
$array[$key] = $value;


답변

공용체 연산자 ( +)를 사용하여 배열을 결합하고 추가 된 배열의 키를 유지할 수 있습니다 . 예를 들면 다음과 같습니다.

<?php

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

print_r($arr3);

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

그래서 당신은 할 수 있습니다 $_GET += array('one' => 1);.

http://php.net/manual/en/function.array-merge.phparray_merge 의 문서에 통합 연산자 사용법에 대한 자세한 정보가 있습니다 .


답변

표에 내 대답을 추가하고 싶습니다.

//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);

이것이 누군가를 도울 수 있기를 바랍니다


답변

정확히 Pekka가 말한 …

또는 원하는 경우 array_merge를 다음과 같이 사용할 수 있습니다.

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

그러나 Pekka의 방법은 훨씬 간단하기 때문에 아마도 선호합니다.


답변

가장 간단한 방법이 아직 게시되지 않은 이유가 궁금합니다.

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


답변

이것은 당신에게 유용 할 수있는 솔루션입니다

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');

덤프 할 때 이와 같은 결과

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)