2016-12-10 1 views
0

나는 프로그래밍에있어 초보자입니다. 아무도이 문제를 도와주세요 제발 도와 줄래?PHP에서 연관 배열을 특정 키로 필터링하는 방법은 무엇입니까?

Array ([product_id] => 1 [sku] => BGM0430 [set] => 9 [type] => simple [categories] => Array ([0] => 3 [1] => 11 [2] => 14) [websites] => Array ([0] => 1) [type_id] => simple [name] => Magical Melody Birthday Card [brand] => 3 [card_number] => XW3M0430 [assortment] => BALASST113 [old_id] => [description] => 
Presidential blue is the background for this happy birthday greeting. A delightful bouquet of multicolored balloons stretches up swirling and dodging little golden stars. "Happy Birthday" is written in large cursive across the front of the card. The message continues at the bottom of the card and says, "To You Happy Birthday." Additional golden foiled stars appear at the sides of the card. 

[short_description] => 
Presidential blue is the background for this happy birthday greeting. A delightful bouquet of multicolored balloons stretches up swirling and dodging little golden stars. "Happy Birthday" is written in large cursive across the front of the card. The message continues at the bottom of the card and says, "To You Happy Birthday." Additional golden foiled stars appear at the sides of the card. 


Message: Wishing you all the best on this wonderful day and throughout the year ahead. 
[verse] => Wishing you all the best on this wonderful day and throughout the year ahead. [card_size] => 7 7/8 x 5 5/8 [card_stock] => 10pt C1S Envirocote 10% PCW LS2467 [url_path] => magical-melody.html [envelope] => Gold Lined White [weight] => 0.0000 [category_ids] => Array ([0] => 3 [1] => 11 [2] => 14) [news_from_date] => [required_options] => 1 [news_to_date] => [has_options] => 1 [status] => 1 [image_label] => Magical Melody Birthday Card, Front [url_key] => magical-melody [visibility] => 4 [small_image_label] => Magical Melody Birthday Card, Front [country_of_manufacture] => [thumbnail_label] => Magical Melody Birthday Card, Front [promotion] => 1 [created_at] => 2013-04-05 17:17:25 [updated_at] => 2013-05-30 15:58:50 [price] => 4.0000 [group_price] => Array () [special_price] => [special_from_date] => [special_to_date] => [tier_price] => Array () [msrp_enabled] => 2 [minimal_price] => [msrp_display_actual_price_type] => 4 [msrp] => [enable_googlecheckout] => 1 [tax_class_id] => 2 [meta_title] => [meta_keyword] => [meta_description] => [is_recurring] => 0 [recurring_profile] => [custom_design] => [custom_design_from] => [custom_design_to] => [custom_layout_update] => [page_layout] => [options_container] => container1 [gift_message_available] =>) Array ([product_id] => 2 [sku] => BBC23567 [set] => 9 [type] => simple [categories] => Array ([0] => 6) [websites] => Array ([0] => 1) [type_id] => simple [name] => Faint Flourish Anniversary Card [brand] => 3 [card_number] => [assortment] => EAASST613 [old_id] => [description] => This beautiful anniversary card with elegant flourish design is a wonderful way to recognize employees for their years of hard work. [short_description] => 
This beautiful anniversary card with elegant flourish design is a wonderful way to recognize employees for their years of hard work. 
Message: Thank you for your hard work and dedication to the team! 

[verse] => Thank you for your hard work and dedication to the team! [card_size] => 8 x 4 11/16 [card_stock] => 100lb 30 % PCW [url_path] => faint-flourish-anniversary-card.html [envelope] => plain white envelope [weight] => 0.0000 [category_ids] => Array ([0] => 6) [news_from_date] => 2013-04-05 00:00:00 [required_options] => 1 [news_to_date] => 2013-04-30 00:00:00 [has_options] => 1 [status] => 1 [image_label] => Faint Flourish Anniversary Card - Front [url_key] => faint-flourish-anniversary-card [visibility] => 4 [small_image_label] => Faint Flourish Anniversary Card - Front [country_of_manufacture] => [thumbnail_label] => Faint Flourish Anniversary Card - Front [promotion] => 0 [created_at] => 2013-04-06 05:47:24 [updated_at] => 2013-05-30 15:34:58 [price] => 4.0000 [group_price] => Array () [special_price] => [special_from_date] => [special_to_date] => [tier_price] => Array () [msrp_enabled] => 2 [minimal_price] => [msrp_display_actual_price_type] => 4 [msrp] => [enable_googlecheckout] => 1 [tax_class_id] => 2 [meta_title] => [meta_keyword] => [meta_description] => [is_recurring] => 0 [recurring_profile] => [custom_design] => [custom_design_from] => [custom_design_to] => [custom_layout_update] => [page_layout] => [options_container] => container1 [gift_message_available] =>) Array ([product_id] => 3 [sku] => BBC23576 [set] => 9 [type] => simple [categories] => Array ([0] => 10) [websites] => Array ([0] => 1) [type_id] => simple [name] => Faint Flourish Get Well [brand] => 3 [card_number] => [assortment] => EAASST613 [old_id] => [description] => This beautiful get well card with elegant flourish design is a wonderful way to share your hopes for a healthier tomorrow. [short_description] => 
This beautiful get well card with elegant flourish design is a wonderful way to share your hopes for a healthier tomorrow. 
Message: Sending many warm thoughts and good wishes. 

[verse] => Sending many warm thoughts and good wishes. [card_size] => 8 x 4 11/16 [card_stock] => 100lb 30 % PCW [url_path] => faint-flourish-get-well.html [envelope] => plain white envelope [weight] => 0.0000 [category_ids] => Array ([0] => 10) [news_from_date] => 2013-04-05 00:00:00 [required_options] => 1 [news_to_date] => 2013-04-30 00:00:00 [has_options] => 1 [status] => 1 [image_label] => Faint Flouish Get Well Card - Front [url_key] => faint-flourish-get-well [visibility] => 4 [small_image_label] => Faint Flouish Get Well Card - Front [country_of_manufacture] => [thumbnail_label] => Faint Flouish Get Well Card - Front [promotion] => 0 [created_at] => 2013-04-06 05:47:24 [updated_at] => 2013-05-07 22:32:09 [price] => 4.0000 [group_price] => Array () [special_price] => [special_from_date] => [special_to_date] => [tier_price] => Array () [msrp_enabled] => 2 [minimal_price] => [msrp_display_actual_price_type] => 4 [msrp] => [enable_googlecheckout] => 1 [tax_class_id] => 2 [meta_title] => [meta_keyword] => [meta_description] => [is_recurring] => 0 [recurring_profile] => [custom_design] => [custom_design_from] => [custom_design_to] => [custom_layout_update] => [page_layout] => [options_container] => container1 [gift_message_available] =>) 

데이터 $product에 저장 (지저분한 형식 죄송합니다)와 어떻게 키가 'SKU', '이름에 해당하는 경우를 제외하고 다른 키 - 값 쌍을 제거 할 수 있습니다

print_r($product) 후 나는 다음을 얻을 수 있습니다 ','price '및'short_description '과 같은 정보를 제공합니다.

다음 스 니펫이 작동하지 않습니다.

foreach($product as $key => $value){ 
    if($key != 'sku' || $key !='name' || $key != 'price' || $key !='short_description'){ 
     unset($product[$key]); 
    } 
} 
var_dump($product); 

어리석은 질문을하면 어떻게 해결할 수 있는지 알려주세요.

모든 답변이나 도움을 주시면 대단히 감사하겠습니다. 미리 감사드립니다.

+1

_ 다음 발췌 문장을 사용할 수 있습니까? _ - 이미 사용해 보셨습니까? – Federkun

+1

'{unset ($ product [$ key]);}' –

+0

@Federkun I (inetail) {ifset ($ key, array ('sku', 'name', 'price', 'short_description' 시도했지만 작동하지 않았다. 편집 해 주셔서 감사합니다. – Lily

답변

1

if 문에있는 조건이 항상 true이므로 해당 스 니펫의 부울 논리가 잘못되었습니다.

if($key != 'sku' && $key !='name' && $key != 'price' 
        && $key !='short_description'){ 

당신은 상태가 조금 짧은 만들기 위해 in_array 기능을 사용할 수 있습니다 :

if (!in_array($key, ['sku','name','price','short_description']) { 
+0

도움을 주셔서 대단히 감사합니다! – Lily

0

당신의 코드에서 어떤 일이 동일하지 않은 경우 조건이 true 될 경우 대신 && 연산자를 사용합니다. 경우와 키 일치의 어떤 다음은 건너 뛸 경우 경우 중 하나와 일치하지 다른 경우 그 당신은, 위의 코드에서 스위치

foreach($product as $key => $value){ 
     switch($key){ 
     case 'sku': 
     case 'name': 
     case 'price': 
     case 'short_description': 
     break; 

     default: 
     unset($product[$key]); 
     } 
} 

을 사용할 수 있습니다, 그것은 사건을 기본값으로 가서 제거합니다 그것.

+0

도움을 주셔서 대단히 감사합니다! – Lily

0

워크 플로우를 유지하기 더 쉬운 것은 원하는 키를 자체 배열에 저장하고 각 키를 확인하는 것입니다. 이제까지 - - 응용 프로그램의 흐름에 다른 값을 필요가 없습니다 당신이 그것의 복사본을 만들어하지 않은 unset는 (배열에서 제거하고 복원 할 수 없습니다, 당신은 결코 경우

$preserve = ['sku', 'name', 'price', 'short_description']; 

foreach($product as $key => $value){ 
    if (!in_array($preserve, $key) { 
     unset($product[$key]); 
    } 
} 

는 다시,이 작품 어딘가에).

원하는 키만 포함 된 새 배열/개체를 만들어 "다른 방향으로"수행 할 수있는보다 유용한 형식으로 제품을 모양 짓고 싶을 수도 있습니다.

$preserve. = ['sku', 'name', 'price', 'short_description']; 
$cleanProduct = []; 

foreach ($preserve as $key) { 
    $cleanProduct[$key] = $product[$key]; 
} 

실제로 $product에 존재하지 않는 키에 대해 잔소리 것 같은이 오히려 본래의 접근법은, 우리는

만 실제로

$preserve. = ['sku', 'name', 'price', 'short_description']; 
$cleanProduct = []; 

foreach ($preserve as $key) { 
    // test if the product has the key. 
    if (isset($product[$key]) { 
    $cleanProduct[$key] = $product[$key]; 
    } 
} 
존재 키를 사용하여 여러 가지 방법

에서 그 문제를 해결할 수 있습니다

$product에없는 키에 null 값을 할당하여 모든 키가 존재하지만 실제 값이 없음을 확인하십시오.

PHP의

최신 버전 (7+)도 할당의 축약 버전 지원 :

$cleanProduct[$key] = $product[$key] ?? null을;

+0

도움을 주셔서 대단히 감사합니다! – Lily

관련 문제