0

Currently I want to output a data from a database. I have two separate arrays. May I know is there a way to combine those arrays. The code is as below,

$array_1 = [
  'memo' => 'title string',
  'break_down' => 'title string',
  'images' => 'title string',
  'email_content' => 'title string'
];

// content from db
$array_2 = [$memo, $break_down, $images, $email_content];


// I want it to display like this
<?php foreach ($array_1 as $key=> $name) : ?>

<p>
<?= $name; ?> = <?php  //content on $array_2 ?> 
<?php //eg: title string = $memo and so on.. ?>
</p>

<?php endforeach ?>
1

1 Answer 1

3

With array_combine and array_keys:

$keys = array_keys($array_1);
$array_2 = array_combine($keys, $array_2);

foreach ($array_1 as $key => $name): ?>
<p>
<?= $name; ?> = <?php echo $array_2[$key]; ...

Note that you can also have the keys you want directly from your SQL query using the as SQL keyword:

select field1 as memo, field2 as break_down ...

and using mysqli_fetch_assoc or PDO::FETCH_ASSOC

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the help. If I use the sql query string, I do not need to assign the array like on $array_2 right?
@Amran: indeed, if you only want to display your query results and if you use as in your query (or if columns have already the good names), you don't need to use array_combine to rebuild a new array.

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.