change key names in array in php - php

ok..I'm trying to re-map the keynames of a key-value array in php using a fieldmap array ie.
i want the $outRow array to hold $inRow['name1'] = 10 to $outRow['name_1'] = 10 for a large set of pre-mapped values..
$fieldmap=array("name1"=>"name_1","name2"=>"name_2");
private function mapRow($inRow) {
$outRow = array();
foreach($inRow as $key => $value) {
$outRow[$this->fieldmap[$key]][] = $value;
}
return $outRow;
} // end mapRow
public function getListings($inSql) {
// get data from new table
$result = mysql_query($inSql);
if (!result) {
throw new exception("retsTranslate SQL Error: $inSql");
}
while ($row = mysql_fetch_assoc($result)) {
$outResult[] = $this->mapRow($row);
}
return $outResult;
} // end getListings
this is not working..I'm getting the array but its using $outResult[0][keyname]...I hope this is clear enough :)

$fieldmap=array("name1"=>"name_1","name2"=>"name_2");
private function mapRow($inRow) {
$outRow = array();
foreach($inRow as $key => $value) {
$outRow[$this->fieldmap[$key]][] = $value;
}
return $outRow;
} // end mapRow
while ($row = mysql_fetch_assoc($result)) {
//$outResult[] = $this->mapRow($row);
$outResult[= $this->mapRow($row);
}
I commented your line of code and added new one..it definitely got what you mentioned in question.

If you can structure your arrays to where the keys align with the values (see example below) you can use PHP array_combine(). Just know that you will need to make absolutely sure the array is ordered correctly.
<?php
$fieldmap = array( 'name_1', 'name_2', 'name_3' );
private function mapRow($inRow)
{
$outRow = array_combine( $this->fieldmap, $inRow );
return $outRow;
}
For example, if your array was:
array( 'name1' => 10, 'name2' => 20, 'name3' => 30 );
The new result would be:
array( 'name_1' => 10, 'name_2' => 20, 'name_3' => 30 );
Let me know if this helps.

Try this:
function mapRow($inRow) {
$outRow = array();
foreach($inRow as $key => $value) {
$outRow[preg_replace('/\d/', '_$0', $key,1)] = $value;
}
return $outRow;
}

Related

How to search multidimensional array with array of keys

Imagine that you have the following data structures. The config one is a hash of config values. The search is an array of hash keys to pull a config value from the config hash.
$config['users']['students']['default']['school'] = 'Garfield High';
$config['users']['students']['default']['domain'] = 'ghs.com';
$config['users']['teacher']['default']['fruit'] = 'apple';
$config['school']['superintendent'] = 'Boris York';
$search[] = 'users';
$search[] = 'students';
$search[] = 'default';
$search[] = 'school';
What's the most efficient way to use the $search array to get the value "Garfield High."
This sounds like a school assignment, but really it isn't. I've wandered down a rabbit hole, and while I'll probably abandon this thing that I'm doing, I'm curious how best to solve this problem. It seems like it should be easy, but for some reason, I'm stumped.
The method to extract values from $config should work with any $search array size. It needs to work with $search = array('school', 'superintendent') as well.
public function get($search, $config) {
// Somehow pull value from $config
}
It's a simple loop, using each element of $search as the key in the next level of the array being searched.
public function get($search, $config) {
$result = $config;
foreach ($search as $key) {
if (is_array($result) && isset($result[$key])) {
$result = $result[$key];
} else {
return false; // not found
}
}
return $result;
}
DEMO
Alternative solution with RecursiveIteratorIterator class:
$config = ['users' => ['students' => ['default' => ['school' => 'Garfield High'], 'highschool' => ['domain' => 'highschool.ghs.com']]]];
$search1 = ['users', 'students', 'default', 'school'];
$search2 = ['users', 'students', 'highschool', 'domain'];
function getConfigItem($search = [], $config = []) {
$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($config), \RecursiveIteratorIterator::SELF_FIRST);
$result = "";
foreach ($iterator as $k => $v) {
if ($search[$iterator->getDepth()] == $k && is_string($v)) {
$result = $v;
}
}
return $result;
}
var_dump(getConfigItem($search1, $config)); // string 'Garfield High'
var_dump(getConfigItem($search2, $config)); // string 'highschool.ghs.com'
http://php.net/manual/en/class.recursiveiteratoriterator.php

codeigniter: alteration of PHP array

i am sending $_POST['checkbox_name'] to function insert_to_table.
function insert_to_table($valid_array)
{
$data_array = array();
$this->load->model('get_data_model');
$updated_max_brand_id = $this->get_data_model->get_max_brand_id();
foreach ($valid_array as $key => $value) {
$data_array['bdc_brand_id'] = $updated_max_brand_id;
$data_array['bdc_cat_id'] = $value;
}
$this->db->insert('mart_brand_dealing_cat',$data_array);
}
the final mysql query should run as below
INSERT INTO `mart_brand_dealing_cat` (`bdc_brand_id`, `bdc_cat_id`) VALUES (11,43),(11,42);
11 - updated_max_brand_id;
42,43 are coming from already existed array $valid_array.
I am trying to insert multiple values at a time.How can i do it. i may wrong please guide and help me.
Your probably looking for something like $this->db->insert_batch();
So for example:
<?php
function insert_to_table($valid_array)
{
$this->load->model('get_data_model');
$brand_id = $this->get_data_model->get_max_brand_id();
$insert = array();
foreach ($valid_array as $key => $cat_id) {
$insert[] = array(
'bdc_brand_id' => $brand_id,
'bdc_cat_id' => $cat_id,
);
}
if (!empty($insert)) {
return $this->db->insert_batch('mart_brand_dealing_cat', $insert);
} else {
return false;
}
}
?>

How to reference cells with specific condition in php multidimensional array

I got an array like this:
$array[0][name] = "Axel";
$array[0][car] = "Pratzner";
$array[0][color] = "black";
$array[1][name] = "John";
$array[1][car] = "BMW";
$array[1][color] = "black";
$array[2][name] = "Peggy";
$array[2][car] = "VW";
$array[2][color] = "white";
I would like to do something like "get all names WHERE car = bmw AND color = white"
Could anyone give advice on how the PHP spell would look like?
function getWhiteBMWs($array) {
$result = array();
foreach ($array as $entry) {
if ($entry['car'] == 'bmw' && $entry['color'] == 'white')
$result[] = $entry;
}
return $result;
}
Edited: This is a more general solution:
// Filter an array using the given filter array
function multiFilter($array, $filters) {
$result = $array;
// Removes entries that don't pass the filter
$fn = function($entry, $index, $filter) {
$key = $filter['key'];
$value = $filter['value'];
$result = &$filter['array'];
if ($entry[$key] != $value)
unset($result[$index]);
};
foreach ($filters as $key => $value) {
// Pack the filter data to be passed into array_walk
$filter = array('key' => $key, 'value' => $value, 'array' => &$result);
// For every entry, run the function $fn and pass in the filter data
array_walk($result, $fn, $filter);
}
return array_values($result);
}
// Build a filter array - an entry passes this filter if every
// key in this array corresponds to the same value in the entry.
$filter = array('car' => 'BMW', 'color' => 'white');
// multiFilter searches $array, returning a result array that contains
// only the entries that pass the filter. In this case, only entries
// where $entry['car'] = 'BMW' AND $entry['color'] = 'white' will be
// returned.
$whiteBMWs = multiFilter($array, $filter);
Doing this in code is more or less emulating what a RDBMS is perfect for. Something like this would work:
function getNamesByCarAndColor($array,$color,$car) {
$matches = array();
foreach ($array as $entry) {
if($entry["color"]== $color && $entry["car"]==$car)
matches[] = $entry["name"];
}
return $matches;
}
This code would work well for smaller arrays, but as they got larger and larger it would be obvious that this isn't a great solution and an indexed solution would be much cleaner.

How to make first array value to uppercase

I am trying to make first array value to uppercase.
Code:
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
So before save($data, $id) to database I want to convert position value to uppercase. I have tried by this
$data['position'] = strtoupper($data['position']);
but than it is not storing the value in db with uppercase but as it is what user inputs.
Current output of $data:
Array ( [position] => it [label] => Information Technology )
And I want it in uppercase as IT
Added Model Method
public function get_positions_array($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
$positions = parent::get($id, $single);
$array = array();
foreach($positions as $pos){
$array[] = get_object_vars($pos);
}
return $array;
}
Main MY_Model method
public function array_from_post($fields)
{
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
This should work:
$data = $this->positions_model->array_from_post(array('position', 'label'));
$data['position'] = strtoupper($data['position']);
$this->positions_model->save($data, $id);
If Its not, then $data array have only read attribute.
The array_from_post() method returns an array with the format below:
$data = array(
'position' => 'it',
'label' => 'Information Technology'
);
So, you could make first value of the array to uppercase, by using array_map or array_walk functions as follows:
$data = array_map(function($a) {
static $i = 0;
if ($i === 0) { $i++; return strtoupper($a); }
else return $a;
}, $array);
Note: This only works on PHP 5.3+, for previous versions, use the function name instead.
Here is the array_walk example, which modifies the $data:
array_walk($data, function(&$value, $key) {
static $i = 0;
if ($i == 0) { $i++; $value = strtoupper($value); }
});
Again, if you're using PHP 5.2.x or lower, you could pass the function name instead.

Get node from php array by one of the fields

I have an array with structure generated like this:
$groups = array();
while ($group = mysql_fetch_array($groups_result)) {
$groups[] = array( 'id' => $group['id'], 'name' => $group['name']);
}
How can I later in the code get the name of the group by its id? For example, I would like a function like:
function get_name_by_id($id, $array);
But I'm looking for some solution which is already implemented in PHP. I know it would be easier to make arrays with array[5] = array('name' => "foo") etc where 5 in this case is id, but in my code there is a lot of arrays already created like i mentioned above and I cannot easily switch it.
$groups = array();
while ($group = mysql_fetch_assoc($groups_result)) {
$groups[$group['id']] = array( 'name' => $group['name']);
}
$name = $groups['beer']['name'];
also please not using fetch_assoc is more efficient than fetch array
function get_name_by_id($id, $data) {
foreach($data as $d) {
if ($d['id'] == $id) {
return $d['name'];
}
}
// return something else, id was not found
}

Categories