반응형
키 값 쌍이 있는 array_param()
값을 추가할 기존 배열이 있습니다.
나는 그것을 실현하기 위해 노력하고 있습니다.array_push()
헛수고다.
다음은 내 코드입니다.
$data = array(
"dog" => "cat"
);
array_push($data['cat'], 'wagon');
내가 이루고 싶은 것은 고양이를 키로서 추가하는 것이다.$data
아래 토막에서와 같이 왜건에 접근할 수 있는 값을 가진 어레이:
echo $data['cat']; // the expected output is: wagon
어떻게 하면 좋을까요?
그렇다면 다음과 같은 것은 어떨까요?
$data['cat']='wagon';
key=>값을 여러 개 추가해야 하는 경우 이 방법을 시도해 보십시오.
$data = array_merge($data, array("cat"=>"wagon","foo"=>"baar"));
$data['cat'] = 'wagon';
이것으로 어레이에 키와 가치를 추가할 수 있습니다.
array_push() 함수를 사용할 필요가 없습니다.새로운 키를 사용하여 새로운 값을 어레이에 직접 할당할 수 있습니다.
$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);
Output:
Array(
[color1] => red
[color2] => blue
[color3] => green
)
예:
$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');
키 값을 변경하는 경우:
$data['firstKey'] = 'changedValue';
//this will change value of firstKey because firstkey is available in array
출력:
어레이 ( [firstKey] => 변경값 [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 )
배열['키'] = 값;
$data['cat'] = 'wagon';
이게 네게 필요한 거야.여기에는 array_push() 함수를 사용할 필요가 없습니다.때로는 문제가 매우 단순하고 복잡한 방식으로 생각할 수 있습니다. :)
<?php
$data = ['name' => 'Bilal', 'education' => 'CS'];
$data['business'] = 'IT'; //append new value with key in array
print_r($data);
?>
결과
Array
(
[name] => Bilal
[education] => CS
[business] => IT
)
그렇게 해 주세요.
$data = [
"dog" => "cat"
];
array_push($data, ['cat' => 'wagon']);
* php 7 이상에서는 ()이 아닌 []를 사용하여 어레이를 만듭니다.
언급URL : https://stackoverflow.com/questions/1355072/array-push-with-key-value-pair
반응형
'programing' 카테고리의 다른 글
Facebook Graph API, 사용자 이메일 받는 방법? (0) | 2022.09.15 |
---|---|
String.replaceAll(RegEx 제외) (0) | 2022.09.15 |
웹 팩을 사용하여 정적 파일을 빌드 디렉토리에 복사하는 방법 (0) | 2022.09.15 |
리스트와 튜플의 차이점은 무엇입니까? (0) | 2022.09.15 |
키스토어 유형: 사용할 키스토어 유형 (0) | 2022.09.15 |