2012-12-12 123 views
1

我有源阵列追加到关联数组?

$A = array(
    0=> array(
     'title'=>'HTML5+CSS3', 
     'teacher'=>'jonh', 
     'id_post'=>1,/* link to $post_formation */ 
     'formation'=>1, 
     'date'=>'12/12/2112' 
    ) 
); 

和一个其它阵列:

$post_formation = array(
      0=>array(1,2,3), 
      1=>array(3,4,5) 
     ) 

查找范围$A操纵新restult(在这种情况下id_post=11=>array(3,4,5)所以将包含更多3 elements

$result = array(
    /* from $A */ 
    0=> array(
     'title'=>'HTML5+CSS3', 
     'teacher'=>'jonh', 
     'id_post'=>1, 

     'formation'=>1, 
     'date'=>'12/12/2112' 
    ), 

    /* Append here more 03 elements `3,4,5` */ 
    1=> array(
     'title'=>'(A)HTML5+CSS3', 
     'teacher'=>'jonh', 
     'id_post'=>1, 

     'formation'=>3, 
     'date'=>'--/--/---' 
    ), 
    2=> array(
     'title'=>'(A)HTML5+CSS3', 
     'teacher'=>'jonh', 
     'id_post'=>1, 

     'formation'=>4, 
     'date'=>'--/--/----' 
    ), 
    3=> array(
     'title'=>'(A)HTML5+CSS3', 
     'teacher'=>'jonh', 
     'id_post'=>1, 

     'formation'=>5, 
     'date'=>'--/--/----' 
    ) 
); 

任何人都可以告诉我这是怎么回事?

+0

我不太明白逻辑。你有什么尝试,你卡在哪里? – deceze

回答

1

虽然有点怪异......

$A=array(array("title"=>"HTML5+CSS3","teacher"=>"john","id_post"=>1,"formation"=>1,"date"=>"12/12/2012")); 
$post_information=array(0=>array(1,2,3),1=>array(3,4,5)); 
print_r($A); 
if(isset($post_information[$A[0]["id_post"]])) 
{ 
    foreach($post_information[$A[0]["id_post"]] as $idx) 
    { 
     $cache=$A[0]; 
     $cache["title"]="(A)".$cache["title"]; 
     $cache["formation"]=$idx; 
     $cache["date"]="--/--/----"; 
     $A[]=$cache; 
    } 
} 
print_r($A); 

结果:

第一print_r

Array 
(
    [0] => Array 
     (
      [title] => HTML+CSS3 
      [teacher] => john 
      [id_post] => 1 
      [formation] => 1 
      [date] => 12/12/2012 
     ) 

) 

第二print_r

Array 
(
    [0] => Array 
     (
      [title] => HTML+CSS3 
      [teacher] => john 
      [id_post] => 1 
      [formation] => 1 
      [date] => 12/12/2012 
     ) 

    [1] => Array 
     (
      [title] => (A)HTML+CSS3 
      [teacher] => john 
      [id_post] => 1 
      [formation] => 3 
      [date] => --/--/---- 
     ) 

    [2] => Array 
     (
      [title] => (A)HTML+CSS3 
      [teacher] => john 
      [id_post] => 1 
      [formation] => 4 
      [date] => --/--/---- 
     ) 

    [3] => Array 
     (
      [title] => (A)HTML+CSS3 
      [teacher] => john 
      [id_post] => 1 
      [formation] => 5 
      [date] => --/--/---- 
     ) 

) 

当然,您可以将逻辑封装在函数中,而不是明文修改源$A

+0

如果array'A'更多的元素可以应用吗? – kn3l

+0

@BandOfBrothers这取决于“更多元素”中的源代码的样子,以及您期望得到的结果是什么。用“更多元素”例子(和预期结果)更新你的问题,我会看看我能否做到。 – Passerby

0

另一种方式,可能更简单

$ArrayPayChannel=array(); 

function array_push_assoc($array, $key, $value){ 
    $array[$key] = $value; 
return $array; 
} 

$ArrayPayChannel = array_push_assoc($ArrayPayChannel, 'Key', 'Value'); 

,如果你的数组,而不是你把面包车另一个array_push_assoc($ ArrayPayChannel,“重点”,“值”)值有更深入;而且你有更深的想象