How can I combine two arrays in into one single array? - php

I am having to add more functionality in my codeigniter project. Here is the jsfiddle demo. I have an array like this:
$faculty = array(2, 3, 4);
and
$message = array('test1', 'test2', 'test3');
I'm also having an last insert id from another database:
$last_inserted_id = 1;
I want to combine the data to form an array like this:
$array = array(array('faculty' => 2, 'message' => 'test1', 'id' => 1),
array('faculty' => 3, 'message' => 'test2', 'id' => 1),
array('faculty' => 4, 'message' => 'test3', 'id' => 1));
Thanks for everyone for your suggestions and time.

I hope this will you:
$array = [];
$faculty = array(2, 3, 4);
$message = array('test1', 'test2', 'test3');
$id = 1;
for ($key = 0; $key < count($faculty); $key++) {
$array[$key]['faculty'] = $faculty[$key];
$array[$key]['message'] = $message[$key];
$array[$key]['id'] = $id;
}
print_r($array);

Related

Merge column values from two arrays to form an indexed array of associative arrays

I have two arrays:
$a = ['0' => 1, '1' => 2, '2' => 3]
$b = ['0' => 4, '1' => 5, '2' => 6]
I want to create a new array like this:
[
['a' => 1, 'b' => '4'],
['a' => '2', 'b' => '5']
]
I have tried using array_merge and array_merge_recursive, but I wasn't able to get the right results.
$data = array_merge_recursive(array_values($urls), array_values($id));
You have to apply array_map() with custom function:
$newArray = array_map('combine',array_map(null, $a, $b));
function combine($n){
return array_combine(array('a','b'),$n);
}
print_r($newArray);
Output:-https://3v4l.org/okML7
Try this one
$c = array_merge($a,$b)
$d[] = array_reduce($d, 'array_merge', []);
It will merge the two array and reduce and remerge it.
You can use foreach to approach this
$a = ['0' => 1, '1' => 2, '2' => 3];
$b = ['0' => 4, '1' => 5, '2' => 6];
$res = [];
$i = 0;
$total = 2;
foreach($a as $k => $v){
$res[$i]['a'] = $v;
$res[$i]['b'] = $b[$k];
$i++;
if($i == $total) break;
}
The idea is to have an array $ab = ['a','b'] and a array from your both arrays like this $merged_array = [[1,4],[2,5],[3,6]]. Now we can combine array $ab with each element of $merged_array and that will be the result we need.
$first = ['0' => 1, '1' => 2, '2' => 3];
$second = ['0' => 4, '1' => 5, '2' => 6];
$merged_array = [];
for($i=0;$i<count($first);$i++)
{
array_push($merged_array,[$first[$i],$second[$i]]);
}
$final = [];
$ab = ['a','b'];
foreach($merged_array as $arr)
{
array_push($final,array_combine($ab, $arr));
}
print_r($final);
All earlier answers are working too hard. I see excessive iterations, iterated function calls, and counter variables.
Because there are only two arrays and the keys between the two arrays are identical, a simple foreach loop will suffice. Just push associative arrays into the result array.
Code: (Demo)
$a = ['0' => 1, '1' => 2, '2' => 3];
$b = ['0' => 4, '1' => 5, '2' => 6];
$result = [];
foreach ($a as $k => $v) {
$result[] = ['a' => $v, 'b' => $b[$k]];
}
var_export($result);
Output:
array (
0 =>
array (
'a' => 1,
'b' => 4,
),
1 =>
array (
'a' => 2,
'b' => 5,
),
2 =>
array (
'a' => 3,
'b' => 6,
),
)

Php Sql Pdo update all users

I got this:
(I am getting the current calender week and the starting day of the week and the ending day of the week)
# DB
$db = DBWrapper::getInstance();
$table = "staff";
$columns = array("id", "firstname", "lastname","categorie_bit","calender_week");
$whereDish = array('categorie_bit = :idDish');
$valuesDish = array('idDish' => 10);
$set = array(
'calender_week' => $newdate,
'start_week' => $startWeek,
'end_week' => $endWeek,
);
$whereWeek = array('id = :id');
echo '<br>'.$db->update($table, $set, $whereWeek, $valuesWeek).'<br>';
how can I make the where statement for the whole ids in the database.
It currently updates one row.
I could write something like this:
$valuesWeek_1 = array('id' => 1);
$valuesWeek_2 = array('id' => 2);
$valuesWeek_3 = array('id' => 3);
$valuesWeek_4 = array('id' => 4);
$valuesWeek_5 = array('id' => 5);
$valuesWeek_6 = array('id' => 6);
$valuesWeek_7 = array('id' => 7);
$valuesWeek_8 = array('id' => 8);
$valuesWeek_9 = array('id' => 9);
But that is not a good solution
you may try something like:
$whereDish = array('categorie_bit IN :idsDish');
$valuesDish = array('idsDish' => array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

PHP re-order values

I have an array like the following:
$content = array(array("id_post" => 1000, "id_user" => 4),
array("id_post" => 1001, "id_user" => 4),
array("id_post" => 1002, "id_user" => 3),
array("id_post" => 1003, "id_user" => 4),
array("id_post" => 1004, "id_user" => 5),
array("id_post" => 1005, "id_user" => 5));
So it means 5 => 1004, 1005 and 4 => 1000, 1001, 1003 and 3 => 1002.
First, how do I get this structure? (possible with commas)
My algorithm for this solution would be something like (here's what I'm asking you guys..how to accomplish this):
$arr = array();
for($i = 0; $i <= count($content) - 1; $i++){
if exists key ($content[$i]['id_user']) IN $arr then
$arr = add_to_existing_key "," . $content[$i]['id_post']
} other wise {
$arr = add_new_key PLUS value $content[$i]['id_user'] <=> $content[$i]['id_post']
}
}
I need the commas so I could parse the info later.
Basically, the objective of this is to do a loop with $arr variable. Imagining that the array would have, finally, something like:
("id_user" => 5, "ids" => '1004,1005'),
("id_user" => 4, "ids" => '1000,1001,1003'),
("id_user" => 3, "ids" => '1002')
for($i = 0; $i <= count($arr) - 1; $i++){
$ids = explode(",", $arr[$i]['ids']);
$info = array();
for($y = 0; $y <= count($ids) - 1; $y++){
$query->("SELECT * FROM table WHERE id = $ids[$y]");
$info[] = array($name, $description);
}
$email->sendEmail($info); // id = 5 => info OF 1004, 1005
$info = array(); // clear array
// loop
// id = 4 => info OF 1000, 1001, 1003
// loop etc
}
Try this:
$arr = array();
// Loop through each content
foreach ($content as $post)
{
$arr[$post['id_user']][] = $post['id_post'];
}
This way, the result would be
$arr = array(
'5'=> array('1004', '1005'),
'4'=> array('1000', '1001', '1003'),
'3'=> array('1002')
);
Then you won't need to use "explode" just to split those comma-separated IDs
Also
I think you might be better off sticking with arrays instead of joining on commas and then exploding later:
foreach($content as $values) {
if(!isset($result[$values['id_user']])) {
$result[$values['id_user']] = array();
}
array_push($result[$values['id_user']], $values['id_post']);
}
print_r($result);
May be this variant will be exactly what you need:
$content = array(array("id_post" => 1000, "id_user" => 4),
array("id_post" => 1002, "id_user" => 3),
array("id_post" => 1004, "id_user" => 5),
array("id_post" => 1003, "id_user" => 4),
array("id_post" => 1001, "id_user" => 4),
array("id_post" => 1005, "id_user" => 5));
// Make preparation array
foreach ( $content as $values ) {
if ( !isset($result[$values['id_user']]) ) {
$result[$values['id_user']] = array();
}
array_push($result[$values['id_user']], $values['id_post']);
}
// Sort inner arrays
foreach ( $result as $key => $valueArray ) {
asort($result[$key]);
}
// Implode arrays to strings
array_walk($result, function(&$array, $key) {
$array = implode(',', $array);
});
// Final array
$result1 = array();
foreach ( $result as $userID => $idsString ) {
$result1[] = array("id_user" => $userID, "id_post" => $idsString);
}
print_r($result1);

how combine multiple arrays into a single associate array using the arrays as keys

I have 2 arrays that i would like to loop through and combine into an associative array. I would like to use the 2 arrays as the keys for the new associative array. I am new to php so any and all help would be appreciated.
$id = array( 2, 4);
$qty = array( 5, 7);
array('id' => , 'qty' => );
Thanks in advance
I would like to output something like this
array(
'id' => 2,
'qty' => 5),
array(
'id'=> 4,
'qty' => 7
)
You can do:
$result = array();
for($i=0;$i<count($id);$i++) {
$result[] = array('id' => $id[$i], 'qty' => $qty[$i]);
}
Added by Mchl:
Alternative, IMHO a bit clearer, but it's matter of opinion mostly
$result = array();
foreach($id as $key => $value) {
$result[] = array('id' => $id[$key], 'qty' => $qty[$key]);
}
Also one-liner w/ lambda (PHP >= 5.3.0) and short array syntax [] (PHP >= 5.4)
$combined = array_map(function($id, $qty) {return ['id' => $id, 'qty' => $qty];}, $id, $qty);
or callback and old array() for earlier versions
function comb($id, $qty)
{
return array('id' => $id, 'qty' => $qty);
}
$combined = array_map('comb', $id, $qty);

where to use array() in PHP

can you give me examples of using array() function ?
There are plenty of examples in the manual:
http://php.net/manual/en/language.types.array.php
more specifically:
http://www.php.net/manual/en/function.array.php
$somearray = array();
$somearray[] = 'foo';
$somearray[] = 'bar';
$someotherarray = array(1 => 'foo', 2 => 'bar');
var_dump($somearray);
echo $someotherarray[2];
$a = array(1, 'test'=>2,'testing'=>'yes');
foreach($a as $key => $value) {
echo $key . ' = ' . $value . '<br />';
}
Even easier to see the output...
print_r($a);
$arr = array(1, 2, 3, 4, 5);
To loop over each element in the array:
foreach($arr as $val) {
print "$var\n";
}
One interesting thing to note about PHP arrays is that they are all implemented as associative arrays. You can specify the key if you want, but if you don't, an integer key is used, starting at 0.
$array = array(1, 2, 3, 4, 5);
is the same as (with keys specified):
$array = array(0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5);
is the same as:
$array = array('0' => 1, '1' => 2, '2' => 3, '3' => 4, '4' => 5);
Though, if you want to start the keys at one instead of zero, that's easy enough:
$array = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5);
Though if you don't specify the key value, it takes the highest key and adds one, so this is a shortcut:
$array = array(1 => 1, 2, 3, 4, 5);
The key (left side) can only be an integer or string, but the value (right side) can be any type, including another array or an object.
Strings for keys:
$array = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5);
Two easy ways to iterate through an array are:
$array = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5);
foreach($array as $value) {
echo "$value\n";
}
foreach($array as $key => $value) {
echo "$key=$value\n";
}
To test to see if a key exists, use isset():
if (isset($array['one'])) {
echo "$array['one']\n";
}
To delete a value from the array, use unset():
unset($array['one']);

Categories