PHP 다중 레벨 객체에서 값을 얻는 간단한 방법
-
16-09-2019 - |
문제
나는 객체의 각 레벨을 반복 할 수 있다는 것을 알고 있지만 이것에 대한 간단한 접근 방식을 원합니다.
QueryResult Object
(
[queryLocator] =>
[done] => 1
[records] => Array
(
[0] => SObject Object
(
[type] => type_1
[fields] =>
[sobjects] => Array
(
[0] => SObject Object
(
[type] => type_2
[fields] =>
[sobjects] => Array
(
[0] => SObject Object
(
[type] => type_3
[fields] =>
[sobjects] => Array
(
[0] => SObject Object
(
[type] => type_4
[fields] =>
[sobjects] => Array
(
[0] => SObject Object
(
[type] => type_5
[fields] =>
[Id] => 12345_I_need_this
)
)
)
)
)
)
)
)
)
)
[size] => 1
)
이 ID 값이 Type_5의 ID 값이 필요합니다. 어떻게 간단한 솔루션에서 얻을 수 있습니까?
생각할 다른 요점 :
- 나는 배열의 대상이 얼마나 크거나 깊이 갈 것인지 알지 못할 것입니다.
나는 재귀에 대해 들었지만 내가 사용할 수 있다고 생각하는 것을 찾지 못했습니다. 어쩌면 더 나은 튜토리얼이 저를 도울 것입니다. 내가 필요한 값의 배열의 일부를 알고 있다면 직접 전화 할 수 있습니까? : $ 객체 [5]-> id ???
해결책
재귀 작동 방식은 다음과 같습니다 (일반적으로)
function recursiveFunctionName( input ) // returns value;
{
//Do something to input to make it new_input
if( isSomethingAccomplished )
{
return value;
}
else
{
return recursiveFunctionName( new_input );
}
}
입력으로 시작하고 유효한 출력을 반환 할 때까지 기능을 계속 호출하도록 함수를 지시합니다. 귀하의 경우에는 이런 식으로 할 수 있습니다.
function getID( SObject $so )
{
// equates to isSomethingAccomplished... You have found the value
// you want returned, so pass that out.
if( $so->id )
{
return $so->id;
}
else
{
// otherwise, this will return the value from the next level,
// pass that out.
# SEE BELOW FOR ONE MORE NOTE HERE.
return getID( $so->sobjects[ 0 ] );
}
}
이제 Sobjects 용 배열을 사용하고 있으므로 아래 줄 아래 줄을 다음과 같이 교체 할 수 있습니다.
$objs = $so->sobjects;
$count = count( $objs );
// Iterate through all of its children, testing each of the child nodes.
// (You're actually using iteration and recursion in combination here).
for( $i = 0; $i < $count; $i++ )
{
$curr = getID( $objs[ $i ] );
// This is the same test as above.
if( $curr )
{
return $curr;
}
}
다른 팁
매우 간단합니다.
class SObject{
/*...*/
public getId(){
if(isset($this->Id)){
return $this->Id;
} else {
return $this->sobjects[0]->getId();
}
}
}
그리고 당신은 전화합니다
$id = $query_obj->getId();
이 구조에서 많은 쿼리를 만들어야하는 경우 이것을 XML로 버리고 XPath를 사용하십시오.
제휴하지 않습니다 StackOverflow