Find matching key in two associate arrays? - php

I'm using codeigniter and I have a returned associated array from db like this:
$result = ['name'=>'john', 'author'=>'smith', 'year'=>2011 ];
And a long list of translated title for the keys saved as an array like this:
$lang = ['name'=>'名字', 'author'=>'作者', 'year'=>'年份', ... ];
I wanted to compare the key of $result to $lang, if a key was used in $result, get its translated title. And at the end, construct an array including all three English title, translated title, and the value:
$lang_result = ['name' =>['名字', 'john'],
'author' =>['作者', 'smith'],
'year' =>['年份', 2011] ]
$data['result'] = $lang_result;
I'm storing into this format because once I passed in these data into views, I wanted to be able to call each one by name
echo "{$result['name'][0]}: {$result['name'][1]} "; // 名字: john
echo "{$result['author'][0]}: {$result['author'][1]} ";
So far I could only achieve this by using foreach -> switch statement
$lang_result = [];
foreach ($result as $key=>$value ) {
switch ($key){
case 'name':
array_push ($lang_result, [ $key => ['名字', $value] ]);
break;
case 'author':
array_push ($lang_result, [ $key => ['作者', $value] ]);
break;
}
}
But as the translated array gets longer, the switch statement will be ridiculously out of hands. What is a better way to simplify this?

As Dan mentioned array_merge_recursive may be what you want. In case you have other logic you need to implement here it is unrolled:
$result = ['name'=>'john', 'author'=>'smith', 'year'=>2011];
$lang = ['name'=>'名字', 'author'=>'作者', 'year'=>'年份'];
$lang_result = [];
foreach ($result as $key=>$value) {
if (array_key_exists($key, $lang)) {
$lang_result[$key] = [$lang[$key], $value];
}
}
// these are the same (for now)
print_r($lang_result);
print_r(array_merge_recursive($lang, $result));

Try using array_merge_recursive
$newArray = array_merge_recursive($result, $lang);

You need to store the keys you want into an array and then do it like so.
$lang_result = array();
$result = ['name'=>'john', 'author'=>'smith', 'year'=>2011 ];
$lang = ['name'=>'名字', 'author'=>'作者', 'year'=>'年份'];
$keys = array('name','author','year');
foreach($keys AS $key){
if(isset($result[$key]) && isset($lang[$key])){
$lang_result[$key] = array($result[$key],$lang[$key]);
}
}

Related

How to loop this array and save to database?

I have this array to save to database:
{"i_barcode_id":["3","3"],"i_barcode_sn":["8999999565404","6933412700043"]}
how do I save it to DB so the databse should be like this.
i_barcode_id i_barcode_sn
3 8999999565404
3 6933412700043
this is my current script.
foreach($myarray as $row){
$dataadd_sto_d = array (
'ID' => $rows['i_barcode_id'],
'SN' => $rows['i_barcode_sn']
);
$insertsto_d = $this->MWarehouse->add_sto_d($dataadd_sto_d); //insert script
};
The script failed to save to database. I do not know why. any
Use this tested working
$key = array();
$value = array();
foreach($myarray as $row){
$id => $rows['i_barcode_id'],
$sn => $rows['i_barcode_sn']
array_push($key, $id);
array_push($value, $sn);
}
$insert_data = array_combine($key, $value);
return $this->MWarehouse->add_sto_d($insert_data);
Note
array_combine() will now throw a ValueError if the numberof elements for each array is not equal; previously this function returned false instead.
You have some typos in your Code like foreach(... as $row) and later you want to access $rows
My Attemp would be, to grap i_barcode_id or i_barcode_sn to loop and take the value index to get the data from the other array.
Example:
//true at the end, cause i have something against stdClass without any reason
$myarray = json_decode('{"i_barcode_id":["3","3"],"i_barcode_sn":["8999999565404","6933412700043"]}',true);
foreach($myarray['i_barcode_id'] as $key => $val){
$insertArray=array(
"ID" => $val,
"SN"=>$myarray['i_barcode_sn'][$key]
);
//Your Insert Script
};

MySQL/PHP - Count the specific values in columns

In a table unit, I have 18 columns which can contain one of three different values in each of the columns. The possible values are 'N', 'I' or 'ETP'.
Three of those columns are:
|------------|-------------|------------|
|gcc_1_1 |gcc_1_2 |gcc_1_3 |
|------------|-------------|------------|
I want to return counts of each of those three values for each column to put into their own variables, e.g. the following variables would be for the first column and the three possible values.
$gcc_1_1_n
$gcc_1_1_i
$gcc_1_1_etp
What would be the simplest way of achieving this in PHP using one MySQL query?
$query = "SELECT * FROM unit";
$result = $connection->query( $query );
while ($row = mysqli_fetch_array($result)) {
...
}
you could do something like this
<?php
$data = [...]; //array of data in the form of [['gcc_1_1' => 'n',... ], ...]
$groupedData = array_reduce(
$data,
function(array $res, array $row){
foreach($row as $column => $value) {
$key = $column.'_'.$value;
$existing = $res[$key] || 0;
$res[$key] = $existing + 1;
}
return $res;
},
[]
);
Now in your $groupedData you have an array with keys that matches your request.
You can use extract() to create n variables but I think you shouldn't do it because it's harder to handle and debug for future issues

PHP: foreach loop with array_merge to create json objects

I'm new to php but i really like like it so far!
Now i stumbled over a problem with array_merge.
This is my code, it simply grabs each table specified in my database then makes it to a big json file.:
$tables = array("buildings", "medical", "other", "tools", "traps", "weapons");
foreach ($tables as $table) {
// Get tables from database
$sth = $db->query("SELECT * FROM $table");
$result = $sth->fetchAll();
// Merge arrays together
if ($arr === null) {
//echo "its 0 <br/> ";
$arr = array( "$table" => $result );
} else {
//echo "more than 0 <br/> ";
$arr2 = array( "$table" => $result );
$merge = array_merge($arr, $arr2);
}
} //End loop
echo $merge;
So far It's working somehow, I manage to get the first table "buildings" and the last table "weapons" to be displayed the way i want perfectly!
But I don't understand why it jumps over the other ones..
I believe it has something to do with $arr2 and that i need to specify a unique array for each of the tables. But how can i achieve this? Is this the way to go or is there a more efficient way to achieve this?
Thanks!
Its failing because of this line
$merge = array_merge($arr, $arr2);
Your merge is always a merge of $arr (which is the first entry in $tables) and $arr2, which is the latest entry being processed. You are not merging the data with the previously merged data, such as
$arr = array_merge($arr, $arr2)
Also, you can get rid of the if/else logic by just starting off by setting $arr to an empty array to start.
$arr = array();
You can put everything inside an unique array, like:
$myArray["$table"] = $result;
$tables = array("buildings", "medical", "other", "tools", "traps", "weapons");
$tableArr = array();
foreach ($tables as $table) {
// Get tables from database
$sth = $db->query("SELECT * FROM $table");
$result = $sth->fetchAll();
if(isset($result)){
$tableArr[$table] = $result;
}else{
$tableArr[$table] = '';
}
} //End loop
print_r($tableArr);
Created new array and set index as table name and store its result in that array.
If I understand correctly...
Instead of this two lines
$arr2 = array( "$table" => $result );
$merge = array_merge($arr, $arr2);
You can try this:
$tables[$table] = $result;
Your code can be greatly simplified.
$tables = array("buildings", "medical", "other", "tools", "traps", "weapons");
foreach ($tables as & $table) {
$table = $db->query("SELECT * FROM $table")->fetchAll();
}
echo json_encode($tables);
Of course, you still need to check for errors (database and JSON errors), in order for the code to be robust, but the simpler you can make something the better. Simple is good, especially when it comes to programming.

PHP -convert one column in 2D array into 1D array specfying column name

I have a 2D array , which holds the result of a mysql query. here is my code
$res=$ $this->dbconnection->Query($Query);
$query_result= array();
while($colRow=mysqli_fetch_array($res))
{
$query_result[]= $colRow;
}
Now i want 1D array which contains all rows under a particular column in $query_result.
For example, the database table contains the fields Name and ID,I know , $query_result[]= $colRow['Name'] will give query results into ID. But I need all rows under Name and Id separately , such as $name= $query_result['Name'],$Id= $query_result['ID'].
Is there any easy way to accomplish this?
Since PHP 5.5.0 you can use...
$myfield_arr = array_column($query_result, 'myfield_name');
... to isolate a column from a two dimensional array.
See http://php.net/manual/en/function.array-column.php
Please try maybe
$res=$ $this->dbconnection->Query($Query);
$query_result= array();
while($colRow=mysqli_fetch_array($res))
{
if (empty($query_result))
$query_result = $colRow;
else
{
foreach ($colRow as $key=> $val)
$query_result[$key][] = $val;
}
}
After clarifying question in comments with you, solution is:
while($colRow=mysqli_fetch_array($res)){
foreach ($colRow as $key => $value) {
if(!isset($query_result[$key])) $query_result[$key]=array();
$query_result[$key][] = $value;
}
}
Use something like this:
foreach ($rows as $key => $value) {
$$key = $value;
}
Converting array of rows into array of columns:
<?php
$arr2dm = [['key1' => 'val11', 'key2' => 'val21'], ['key1' => 'val12', 'key2' => 'val22']];
foreach ($arr2dm as $arr) {
foreach ($arr as $k => $v) {
$res[$k][] = $v;
}
}
print_r($res);
http://sandbox.onlinephpfunctions.com/code/514050d07f9ed599e010ccd11e51fc18e39647fa

Adding to a multidimensional array in PHP

I have an array being returned from the database that looks like so:
$data = array(201 => array('description' => blah, 'hours' => 0),
222 => array('description' => feh, 'hours' => 0);
In the next bit of code, I'm using a foreach and checking the for the key in another table. If the next query returns data, I want to update the 'hours' value in that key's array with a new hours value:
foreach ($data as $row => $value){
$query = $db->query('SELECT * FROM t WHERE id=$row');
if ($result){
$value['hours'] = $result['hours'];
}
It's all fine except that I've tried just about every combination of declarations for the foreach loop, but I keep getting the error that the $value['hours'] is an invalid reference. I've tried declaring $value[] ... but that doesn't work either. I don't need to iterate through $value so another foreach loop isn't necessary.
Surely this is easier than my brain is perceiving it.
Here's the whole snippet:
foreach($_gspec as $key => $value){
$sql = sprintf('SELECT * FROM List WHERE specialtyID=%s', $key);
$query = $db->query($sql);
if ($query->num_rows() !== 0){
$result = $query->row_array();
$value['hours'] = $result['hours'];
}
}
You want
$data[$row]['hours'] = $result['hours']
$row would be better named as $key (that is what it is!)
Some people would suggest using pointers, but I find this way makes more sense to me.
You need to use ampersand in front of the $value in foreach to pass it by reference like this:
foreach ($data as $row => &$value){
$query = $db->query($sql);
if ($result){
$value['hours'] = $result['hours'];
}
}
More info here: http://php.net/manual/en/control-structures.foreach.php
As of PHP 5, you can easily modify
array's elements by preceding $value
with &. This will assign reference
instead of copying the value.
Use reference ->
foreach ($data as $row => & $value) {
$query = $db->query('SELECT * FROM t WHERE id=$row');
// [...]
if ($result) {
$value['hours'] = $result['hours'];
}
}

Categories