0

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 ?

5 Answers 5

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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
        )

)

Comments

1

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 )

Comments

0

Change to:

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

Comments

0
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',
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.