2010-12-21 26 views
11

मैं एक पाश में इस तरह एक सरणी बनाने के लिए कोशिश कर रहा हूँ में एक बहुआयामी सरणी बनाएँ: इस कोड के साथएक पाश

$dataPoints = array(
    array('x' => 4321, 'y' => 2364), 
    array('x' => 3452, 'y' => 4566), 
    array('x' => 1245, 'y' => 3452), 
    array('x' => 700, 'y' => 900), 
    array('x' => 900, 'y' => 700)); 

$dataPoints = array();  
$brands = array("COCACOLA","DellChannel","ebayfans","google", 
    "microsoft","nikeplus","amazon"); 
foreach ($brands as $value) { 
    $resp = GetTwitter($value); 
    $dataPoints = array(
     "x"=>$resp['friends_count'], 
     "y"=>$resp['statuses_count']); 
} 

लेकिन जब पाश पूरा करता है मेरी सरणी इस तरह दिखता है:

Array ([x] => 24 [y] => 819) 

उत्तर

23

इसका कारण यह है कि आप कर रहे हैं प्रत्येक पाश पर एक नई सरणी के रूप में फिर से बताए $dataPoints है। यह करने के लिए

बदलें:

$dataPoints[] = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']); 

यह हर यात्रा आप $ datapoints चर अधिलेखित रहे $dataPoints

1
$dataPoints[] = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']); 
0

के अंत में एक नई सरणी में संलग्न कर देगा, लेकिन आप के लिए नए तत्वों को जोड़ने चाहिए सरणी ...

$dataPoints[] = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']);

2

array_merge($array1,$array2) का उपयोग करें पुनरावृत्ति में उपयोग के लिए दो सरणी का उपयोग करें और दूसरा अंतिम परिणाम संग्रहीत करने के लिए। कोड चेकआउट करें।

$dataPoints = array(); 
$dataPoint = array(); 

$brands = array(
    "COCACOLA","DellChannel","ebayfans","google","microsoft","nikeplus","amazon"); 
foreach($brands as $value){ 
    $resp = GetTwitter($value); 
    $dataPoint = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']); 
    $dataPoints = array_merge($dataPoints,$dataPoint); 
}