PHP의 배열에서 단일 값을 얻는 방법

小云云
풀어 주다: 2023-03-22 11:54:02
원래의
2066명이 탐색했습니다.

이 글은 주로 PHP의 배열에서 단일 값을 추출하는 방법을 공유합니다. 주로 코드 형식으로 공유됩니다.

php는 배열에서 단일 값을 가져옵니다
1. 배열 arr
var_dump(arr)의 값은 다음과 같습니다.

array (size=3)  'delete' => 
    array (size=3)      0 => string 'HBSFlyRecode20170222-101501.txt' (length=31)      1 => string 'HBSFlyRecode20170222-105502.txt' (length=31)      2 => string 'HBSFlyRecode20170222-108803.txt' (length=31)  'new' => 
    array (size=3)      0 => string 'HBSFlyRecode20170223-101504.txt' (length=31)      1 => string 'HBSFlyRecode20170223-105505.txt' (length=31)      2 => string 'HBSFlyRecode20170223-108806.txt' (length=31)  'old' => 
    array (size=3)      0 => string 'HBSFlyRecode20170221-101507.txt' (length=31)      1 => string 'HBSFlyRecode20170221-105508.txt' (length=31)      2 => string 'HBSFlyRecode20170221-108809.txt' (length=31)
로그인 후 복사
echo $arr['old'][0];
打印出: HBSFlyRecode20170221-101507.txt
로그인 후 복사

그러나 arr이 객체 형식인 경우 인쇄 결과는 다음과 같습니다.
var_dump(arr) )

object(stdClass)[1]  public 'delete' => 
    array (size=3)      0 => string 'HBSFlyRecode20170222-101501.txt' (length=31)      1 => string 'HBSFlyRecode20170222-105502.txt' (length=31)      2 => string 'HBSFlyRecode20170222-108803.txt' (length=31)  public 'new' => 
    array (size=3)      0 => string 'HBSFlyRecode20170223-101504.txt' (length=31)      1 => string 'HBSFlyRecode20170223-105505.txt' (length=31)      2 => string 'HBSFlyRecode20170223-108806.txt' (length=31)  public 'old' => 
    array (size=3)      0 => string 'HBSFlyRecode20170221-101507.txt' (length=31)      1 => string 'HBSFlyRecode20170221-105508.txt' (length=31)      2 => string 'HBSFlyRecode20170221-108809.txt' (length=31)
로그인 후 복사

$arr['old'][0]을 사용하여 값을 얻을 수 없습니다. arr 객체 및 배열에 공통적인 foreach 메서드를 사용하여 값을 얻을 수 있습니다.

function getValue($arr){

    foreach($arr as $key => $value){        if(is_array($value)){
            getValue($value);
        }else{            echo $value."<br>";
        }

    }
}
로그인 후 복사

arr이 객체 형식인 경우 다음은 객체를 배열 형식으로 변환할 수 있습니다.

1. $object_json = json_encode($arr);得到的是对象   $json = json_encode($arr,true);得到的是纯json2. json_decode($object_json) 和 json_decode($json)得到的是数组对象
    json_decode($object_json,true) 和 json_decode($json,true)得到的是数组

综上 , 可以将数组对象转为数组的方式:
로그인 후 복사

arr,true),true);

项目中发现此问题 , 建议大家在php中将json和array转换时 , json_encode() 和 json_decode()的第二个参数要加 true , 即:
로그인 후 복사

json_encode(

json,true);

위 내용은 PHP의 배열에서 단일 값을 얻는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!