Hai Truong IT
Hai Truong IT

Reputation: 4187

Php error only get a value in array?

I have a sample code:

$link = array('google.com', 'facebook.com');
$name = array('google', 'facebook');

$data = array();
for($i=0; $i<count($link); $i++) {
   $data['name'] = $name[$i];
   $data['link'] = $link[$i];
}
print_r($data);

=> result on show Array ( [name] => facebook [link] => facebook.com ) , not show all, how to fit it ?

Upvotes: 0

Views: 98

Answers (5)

jsteinmann
jsteinmann

Reputation: 4752

keep it simple, all you're doing is combining two arrays into an associative array, so use the native functionality of php. Using a loop to do this is a performance hit and unnecessary unless you plan on displaying the count.

<?php
    $names = array('google', 'facebook');
    $links = array('google.com', 'facebook.com');
    $data = array_combine($names, $links);
    print_r($data);
?>

result: Array ( [google] => google.com [facebook] => facebook.com )

Upvotes: 1

Levin
Levin

Reputation: 194

try:

$data[$i]['name'] = $name[$i];
$data[$i]['link'] = $link[$i];

out:

Array
(
    [0] => Array
        (
            [name] => google
            [link] => google.com
        )

    [1] => Array
        (
            [name] => facebook
            [link] => facebook.com
        )

)

Upvotes: 1

Nemoden
Nemoden

Reputation: 9056

for($i=0; $i<count($link); $i++) {
   $data[] = array('name' => $name[$i], 'link' => $link[$i]);
}

or:

foreach ($link as $index => $url) {
    $data[] = array('name' => $name[$index], 'link' => $url);
}

another good solution is to go with array_combine:

array_combine($name,$link);

result of applying array_combine:

array (
  'google' => 'google.com',
  'facebook' => 'facebook.com',
)

Upvotes: 0

Sithu
Sithu

Reputation: 4862

The variable $data should be a multi-dimensional array. Otherwise, the latest data overwrites the previous one.
Try this.

$link = array('google.com', 'facebook.com');
$name = array('google', 'facebook');

$data = array();
for($i=0; $i<count($link); $i++) {
   $data[] = array(
        'name' => $name[$i],
        'link' => $link[$i]
   );
}
print_r($data);

Upvotes: 1

xdazz
xdazz

Reputation: 160833

Change to:

   $data[$i]['name'] = $name[$i];
   $data[$i]['link'] = $link[$i];

Upvotes: 0

Related Questions