So I have multiples empty arrays that I want to fill, let's say
$a_tab = [];
$b_tab = [];
$c_tab = [];
I have an array containing some data, let's say
$data = ['a' => 'foo', 'b' => 'bar', 'c' => 'foobar'];
I wanted to be able to do something like this :
foreach($data as $key => $value) {
$tab_name = $key . '_tab'; // so we have a variable that have the same name as one of the array we declared before
$$tab_name[$value] = $value; // this should add 'foo' into $a_tab, 'bar' in $b_tab and 'foobar' in $c_tab
}
But no value is ever added to any array...
Could someone explain me what did I do wrong ?
PS : if you don't want pseudo-code, here is the code that I had when I faced the issue :
// $tab is a parameter of the current function
$done_courses = []; // the array where we are going to put every courses that already have been added in one bifurcation tab
$regex_wz = '/\_werkzoekende/';
$regex_bd = '/\_bediende/';
$regex_op = '/\_outplacement/';
$bifurcation_keys = ['wz_tab' => $regex_wz, 'bd_tab' => $regex_bd, 'op_tab' => $regex_op];
// create the 3 arrays
$wz_tab = [];
$bd_tab = [];
$op_tab = [];
foreach($tab as $key => $value) {
foreach($bifurcation_keys as $tab_name => $regex) {
if(preg_match($regex, $key)) {
$n_k = preg_replace($regex, '', $key);
$$tab_name[$n_k] = $value;
if(!isset($done_courses[$n_k])) {
$done_courses[$n_k] = $n_k;
}
}
}
}
Did you try..
foreach($data as $key => $value) {
${$key.'_tab'}[$value] = $value;
}
Related
I have this general data structure:
$levels = array('country', 'state', 'city', 'location');
I have data that looks like this:
$locations = array(
1 => array('country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'count'=>123),
2 => array('country'=>'Germany', ... )
);
I want to create hierarchical arrays such as
$hierarchy = array(
'USA' => array(
'New York' => array(
'NYC' => array(
'Central Park' => 123,
),
),
),
'Germany' => array(...),
);
Generally I would just create it like this:
$final = array();
foreach ($locations as $L) {
$final[$L['country']][$L['state']][$L['city']][$L['location']] = $L['count'];
}
However, it turns out that the initial array $levels is dynamic and can change in values and length So I cannot hard-code the levels into that last line, and I do not know how many elements there are. So the $levels array might look like this:
$levels = array('country', 'state');
Or
$levels = array('country', 'state', 'location');
The values will always exist in the data to be processed, but there might be more elements in the processed data than in the levels array. I want the final array to only contain the values that are in the $levels array, no matter what additional values are in the original data.
How can I use the array $levels as a guidance to dynamically create the $final array?
I thought I could just build the string $final[$L['country']][$L['state']][$L['city']][$L['location']] with implode() and then run eval() on it, but is there are a better way?
Here's my implementation. You can try it out here:
$locations = array(
1 => array('country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'count'=>123),
2 => array('country'=>'Germany', 'state'=>'Blah', 'city'=>'NY', 'location'=>'Testing', 'count'=>54),
);
$hierarchy = array();
$levels = array_reverse(
array('country', 'state', 'city', 'location')
);
$lastLevel = 'count';
foreach ( $locations as $L )
{
$array = $L[$lastLevel];
foreach ( $levels as $level )
{
$array = array($L[$level] => $array);
}
$hierarchy = array_merge_recursive($hierarchy, $array);
}
print_r($hierarchy);
Cool question. A simple approach:
$output = []; //will hold what you want
foreach($locations as $loc){
$str_to_eval='$output';
for($i=0;$i<count($levels);$i++) $str_to_eval .= "[\$loc[\$levels[$i]]]";
$str_to_eval .= "=\$loc['count'];";
eval($str_to_eval); //will build the array for this location
}
Live demo
If your dataset always in fixed structure, you might just loop it
$data[] = [country=>usa, state=>ny, city=>...]
to
foreach ($data as $row) {
$result[][$row[country]][$row[state]][$row[city]] = ...
}
In case your data is dynamic and the levels of nested array is also dynamic, then the following is an idea:
/* convert from [a, b, c, d, ...] to [a][b][...] = ... */
function nested_array($rows, $level = 1) {
$data = array();
$keys = array_slice(array_keys($rows[0]), 0, $level);
foreach ($rows as $r) {
$ref = &$data[$r[$keys[0]]];
foreach ($keys as $j => $k) {
if ($j) {
$ref = &$ref[$r[$k]];
}
unset($r[$k]);
}
$ref = count($r) > 1 ? $r : reset($r);
}
return $data;
}
try this:
<?php
$locations = [
['country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'street'=>'7th Ave', 'count'=>123],
['country'=>'USA', 'state'=>'Maryland', 'city'=>'Baltimore', 'location'=>'Harbor', 'count'=>24],
['country'=>'USA', 'state'=>'Michigan', 'city'=>'Lansing', 'location'=>'Midtown', 'building'=>'H2B', 'count'=>7],
['country'=>'France', 'state'=>'Sud', 'city'=>'Marseille', 'location'=>'Centre Ville', 'count'=>12],
];
$nk = array();
foreach($locations as $l) {
$jsonstr = json_encode($l);
preg_match_all('/"[a-z]+?":/',$jsonstr,$e);
$narr = array();
foreach($e[0] as $k => $v) {
if($k == 0 ) {
$narr[] = '';
} else {
$narr[] = ":{";
}
}
$narr[count($e[0]) -1] = ":" ;
$narr[] = "";
$e[0][] = ",";
$jsonstr = str_replace($e[0],$narr,$jsonstr).str_repeat("}",count($narr)-3);
$nk [] = $ko =json_decode($jsonstr,TRUE);
}
print_r($nk);
Database have three field:
here Name conatin contry state and city name
id,name,parentid
Pass the contry result to array to below function:
$data['contry']=$this->db->get('contry')->result_array();
$return['result']=$this->ordered_menu( $data['contry'],0);
echo "<pre>";
print_r ($return['result']);
echo "</pre>";
Create Function as below:
function ordered_menu($array,$parent_id = 0)
{
$temp_array = array();
foreach($array as $element)
{
if($element['parent_id']==$parent_id)
{
$element['subs'] = $this->ordered_menu($array,$element['id']);
$temp_array[] = $element;
}
}
return $temp_array;
}
Suppose, i have the fallowing json:
{
"foo.bar": 1
}
and i want to save this like this:
$array["foo"]["bar"] = 1
but i also can have more than 2 "parameters" in string. For example:
{
"foo.bar.another_foo.another_bar": 1
}
and i want to save this same way.
$array["foo"]["bar"]["another_foo"]["another_bar"] = 1
Any ideas how can i do that in case that i don't know how many parameters i have?
This is far from the nicest solution, but I've been programming all day so I'm a little tired, but I hope it gives you something to work off, or at least a working solution for the time being.
Here's the IDEone of it working: click
And here's the code:
$json = '{
"foo.bar": 1
}';
$decoded = json_decode($json, true);
$data = array();
foreach ($decoded as $key => $value) {
$keys = explode('.', $key);
$data[] = buildNestedArray($keys, $value);
}
print_r($data);
function buildNestedArray($keys, $value) {
$new = array();
foreach ($keys as $key) {
if (empty($new)) {
$new[$key] = $value;
} else {
array_walk_recursive($new, function(&$item) use ($key, $value) {
if ($item === $value) {
$item = array($key => $value);
}
});
}
}
return $new;
}
Output:
Array
(
[0] => Array
(
[foo] => Array
(
[bar] => 1
)
)
)
Wasn't sure whether your JSON string could have multiples or not so I made it handle the former.
Hope it helps, may come back and clean it up a bit in the future.
Start with a json_decode
Then build a foreach loop to break apart the keys and pass them to some kind of recursive function that creates the values.
$old_stuff = json_decode($json_string);
$new_stuff = array();
foreach ($old_stuff AS $key => $value)
{
$parts = explode('.', $key);
create_parts($new_stuff, $parts, $value);
}
Then write your recursive function:
function create_parts(&$new_stuff, $parts, $value)
{
$part = array_shift($parts);
if (!array_key_exists($part, $new_stuff)
{
$new_stuff[$part] = array();
}
if (!empty($parts)
{
create_parts($new_stuff[$part], $parts, $value);
}
else
{
$new_stuff = $value;
}
}
I have not tested this code so don't expect to just cut and past but the strategy should work. Notice that $new_stuff is passed by reference to the recursive function. This is very important.
Try the following trick for "reformatting" into json string which will fit the expected array structure:
$json = '{
"foo.bar.another_foo.another_bar": 1
}';
$decoded = json_decode($json, TRUE);
$new_json = "{";
$key = key($decoded);
$keys = explode('.', $key);
$final_value = $decoded[$key];
$len = count($keys);
foreach ($keys as $k => $v) {
if ($k == 0) {
$new_json .= "\"$v\"";
} else {
$new_json .= ":{\"$v\"";
}
if ($k == $len - 1) $new_json .= ":$final_value";
}
$new_json .= str_repeat("}", $len);
var_dump($new_json); // '{"foo":{"bar":{"another_foo":{"another_bar":1}}}}'
$new_arr = json_decode($new_json, true);
var_dump($new_arr);
// the output:
array (size=1)
'foo' =>
array (size=1)
'bar' =>
array (size=1)
'another_foo' =>
array (size=1)
'another_bar' => int 1
$Ascore = 30
$Bscore = 30
$Cscore = 20
$Dscore = 20
$data = array(
'A1' => $Ascore,
'B1' => $Bscore,
'C1' => $Cscore,
'D1' => $Dscore
);
$highest = max($data);
foreach($data as $key => $value){
if($value === $highest){
echo $key;
//echo output (t1,t3);
}
something like this
getting them store in different variables
$type1 = $key[0]; //this will be t1//
$type2 = $key[1]; //this will be t3//
My intention is to somehow make the element I found at $key and put them into different variable , how I'm going to achieve that? As I have the idea but I cant get it work on.
Assuming I'm reading the question correctly, because it is a bit vague:
$data = [1,3,5,3,5];
$highest = max($data);
$result = array_keys(
array_filter(
$data,
function($value) use ($highest) {
return $value == $highest;
}
)
);
var_dump($result);
Do you mean store the keys where the corresponding value is the maximum value in the array? If so try:
$highest = max($data);
$max_keys = array();
foreach($data as $key => $value){
if ($value === $highest){
array_push($max_keys, $key);
}
}
If you must have the keys in separate variables just add:
list($type1, $type2) = $max_keys;
I am having trouble getting my php script to work when using a function in if statements.
The code currently runs, but doesn't give me any information, nor any errors, if I remove the IF'S it works fine, but the project I am working on, this is essential.
Here is my code - I have took out the SQL to save space..
if ($VAR === 'PK%') {
CDB::UseDB('blah', 'blah', 'blah', 'blah');
$sql = "blah blah
";
$lrs = CDB::ExecuteQuery($sql);
if ($lrs) {
$jsonData = convert($lrs);
function convert($lrs)
{
// RE-GET VARIABLE AS IT CAN'T GET IT FROM OUTSIDE OF FUNCTION
$VAR = $_GET['VARIABLE'];
$intermediate = array();
while ($vals = CDB::GetAssoc($lrs)) {
$key = $vals['VAR'];
$y = $vals['MEASURE_1'];
if (!isset($intermediate[$key])) $intermediate[$key] = array();
$intermediate[$key][] = array('x' => count($intermediate[$key]), 'y' => $y);
}
$output = array();
foreach ($intermediate as $key => $values) {
$output[] = array(
"key" => $key,
'values' => $values
);
}
return json_encode($output, JSON_NUMERIC_CHECK);
}
}
}
Can anyone shed some light on what I am doing wrong?
You are defining your function in a conditional way. In that case its definition must be processed prior to being called.
I would recommend declaring your function separately and then use it, like:
function convert($lrs) {
// RE-GET VARIABLE AS IT CAN'T GET IT FROM OUTSIDE OF FUNCTION
$VAR = $_GET['VARIABLE'];
$intermediate = array();
while ($vals = CDB::GetAssoc($lrs)) {
$key = $vals['VAR'];
$y = $vals['MEASURE_1'];
if (!isset($intermediate[$key])) $intermediate[$key] = array();
$intermediate[$key][] = array('x' => count($intermediate[$key]), 'y' => $y);
}
$output = array();
foreach ($intermediate as $key => $values) {
$output[] = array(
"key" => $key,
'values' => $values
);
}
return json_encode($output, JSON_NUMERIC_CHECK);
}
if ($VAR === 'PK%') {
CDB::UseDB('blah', 'blah', 'blah', 'blah');
$sql = "blah blah";
$lrs = CDB::ExecuteQuery($sql);
if ($lrs) {
$jsonData = convert($lrs);
}
}
I have the following code
while($row = $usafisRSP->fetch_assoc()) {
$id = $row['id'];
$Applicantid = $row['Applicantid'];
$unique_num = $row['unique_num'];
// .................
$hidden_fields = array($Applicantid, $unique_num, $regs_t ....);
$hidden_values = array();
foreach ($hidden_fields as $key => $value) {
$hidden_values[$value] = "$key = ".base64_decode($value)."<br>";
echo $hidden_values[$value];
}
}
and the result is something like this
0 = 116153840
1 = 136676636
2 = 2010-12-17T04:12:37.077
3 = XQ376
4 = MUKANTABANA
I would like to replace 0, 1, 2, 3 etc with some custom values like "Id", "application name" to make the result like
id = 116153840
application name = 136676636
etc ..
how can I do that ?
Replace the $hidden_fields = array(... line with the following:
$hidden_keys = array('id', 'Applicantid', 'unique_num');
$hidden_fields = array_intersect_key($row, array_fill_keys($hidden_keys, NULL));
If you want to suppress all fields with value 0, either use
$hidden_fields = array_filter($hidden_fields, function($v) {return $v != 0;});
(this will completely omit the 0-entries) or
$hidden_fields = array_map($hidden_fields, function($v) {return ($v==0?'':$v);});
(this will leave them blank). If you're using an older version than 5.3, you'll have to replace the anonymous functions with calls to create_function.
I assume not every field in your row should be a hidden field. Otherwise you could just do $hidden_fields = $row.
I would create an array that specifies the hidden fields:
$HIDDEN = array(
'id' => 'Id',
'Applicantid' => 'application name',
'unique_num' => 'whatever'
);
And then in your while loop:
while(($row = $usafisRSP->fetch_assoc())){
$hidden_fields = array();
foreach$($HIDDEN as $field=>$name) {
$hidden_fields[$name] = $row[$field];
}
//...
foreach($hidden_fields as $name => $value) {
$hidden_fields[$name] = $name . ' = ' . base64_decode($value);
echo $hidden_values[$name];
// or just echo $name, ' = ',$hidden_fields[$value];
}
}
foreach ($row as $key => $value) {
$hidden_values[$value] = "$key = ".base64_decode($value)."<br>";
echo $hidden_values[$value];
}
This could give you something relevant. Through accessing the string keys from the row array which contains the string keys