아래 코드는 아래 XML 파일에서 "store"요소의 값을 검색하고 값을 배열 (storeArray)에 삽입하는 데 사용됩니다. 중복 값을 배열에 넣기를 원하지 않으므로 (즉 Best Buy가 두 번 삽입되는 것을 원하지 않습니다) 중복을 방지하기 위해 in_array 메서드를 사용하고 있습니다.
이 코드는 중복을 방지하지 않습니다 (IE Best Buy가 두 번 표시됨).
$xmlDoc = simplexml_load_file("products.xml");
$storeArray = array();
foreach($xmlDoc->product as $Product) {
echo "Name: " . $Product->name . ", ";
echo "Price: " . $Product->price . ", ";
if( !in_array( $Product->store, $storeArray )) {
$storeArray[] = $Product->store;
}
}
foreach ($storeArray as $store) {
echo $store . "<br>";
}
그러나이 코드는 작동합니다.
$practiceArray = array('Product1', 'Product2', 'Product3');
if (in_array("Product1", $practiceArray)) {
echo "Is in array";}
else {
echo "NOT in array";
}
어떤 충고?
다음은 XML 파일입니다.
<products>
<product type="Electronics">
<name> Desktop</name>
<price>499.99</price>
<store>Best Buy</store>
</product>
<product type="Electronics">
<name>Lap top</name>
<price>599.99</price>
<store>Best Buy</store>
</product>
<product type="Hardware">
<name>Hand Saw</name>
<price>99.99</price>
<store>Lowes</store>
</product>
</products>
이것을 시도하십시오
if( !in_array( (string)$Product->store, $storeArray )) {
$storeArray[] = (string)$Product->store;
}
$Product->store
은 문자열이 아니기 때문에 SimpleXMLElement
객체입니다. 따라서 조작하기 전에 문자열로 캐스팅해야합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다