IT story

키 값 쌍을 가진 array_push ()

hot-time 2020. 5. 25. 08:08
반응형

키 값 쌍을 가진 array_push ()


값을 추가하려는 기존 배열이 있습니다.

나는 array_push()쓸모없는 것을 사용하려고 노력하고 있습니다.

아래는 내 코드입니다.

$data = array(
    "dog" => "cat"
);

array_push($data['cat'], 'wagon');

내가 달성하고자하는 것은 고양이 를 값 $data으로 웨건 이있는 배열에 키로 추가 하여 아래 스 니펫과 같이 액세스하는 것입니다.

echo $data['cat']; // the expected output is: wagon

어떻게하면 되나요?


따라서 다음과 같은 것은

$data['cat']='wagon';

여러 키 => 값을 추가 해야하는 경우이를 시도하십시오.

$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));

$data['cat'] = 'wagon';

이것이 배열에 키와 값을 추가하는 데 필요한 전부입니다.


예를 들어 :

$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');

키 값을 변경하는 경우 :

$data['firstKey'] = 'changedValue'; 
//this will change value of firstKey because firstkey is available in array

산출:

배열 ([firstKey] => changedValue [secondKey] => secondValue)

새 키 값 쌍을 추가하려면 다음을 수행하십시오.

$data['newKey'] = 'newValue'; 
//this will add new key and value because newKey is not available in array

산출:

배열 ([firstKey] => firstValue [secondKey] => secondValue [newKey] => newValue)


적절한 구문은 다음과 같습니다.

$array = array("color1"=>"red", "color2"=>"blue");
array_push($array['color3']='green'); 

그냥 그렇게하십시오 :

$data = [
    "dog" => "cat"
];

array_push($data, ['cat' => 'wagon']);

* PHP 7 이상에서는 ()가 아닌 []를 사용하여 배열을 생성합니다.

참고 URL : https://stackoverflow.com/questions/1355072/array-push-with-key-value-pair

반응형