How to nest 3 arrays in php - php

I need to nest 3 arrays (so the first array contains an array, which also contains an array). Im having success with 2 arrays but I can't get 3 to work.
I had my code working with 2 arrays (which worked jusr fine) but I can't get 3 arrays to be nested.
My current code:
if (!empty($sections)) {
foreach ($sections as $d) {
$row_array = array();
$row_array["id"] = intval($d["id"]);
$row_array["sname"] = $d["sname"];
$row_array["sicon"] = $d["sicon"];
$row_array["perc"] = intval($d["perc"]);
$row_array["pvalue"] = intval($d["pvalue"]);
$row_array["vfixed"] = intval($d["vfixed"]);
$row_array["sectionValues"] = array();
array_push($row_array["sectionValues"],
intval($d["perc"]),
intval($d["id"]),
0
);
$row_array["sectionIndicators"] = array();
//loop indicators
if (!empty($indicators)) {
foreach ($indicators as $v) {
if ($d["id"] == $v["idsec"]) {
/*$row_array["sectionIndicators"][] = array(
"iid" => intval($v["iid"]),
"iname" => $v["iname"],
"perc" => intval($v["perc"]),
"pvalue" => intval($v["pvalue"]),
"vfixed" => intval($v["vfixed"])
);*/
$row_array["sectionIndicators"]["iid"] = intval($v["iid"]);
$row_array["sectionIndicators"]["iname"] = $v["iname"];
$row_array["sectionIndicators"]["perc"] = intval($v["perc"]);
$row_array["sectionIndicators"]["pvalue"] = intval($v["pvalue"]);
$row_array["sectionIndicators"]["vfixed"] = intval($v["vfixed"]);
$row_array["sectionIndicators"]["finalArray"] = array();
}
}
}
array_push($data, $row_array);
}
}
The part that I commented out is my working part (with 2 arrays).The new part works but only contains the last row of $indicators so it seems like the loop isn't working this way.
The $row_array["sectionIndicators"]["finalArray"] = array(); will contain the last nested array.
Any help is much appreciated.
SOLUTION
I found out that I had to give an index. My solution:
if (!empty($sections)) {
foreach ($sections as $d) {
$row_array = array();
$row_array["id"] = intval($d["id"]);
$row_array["sname"] = $d["sname"];
$row_array["sicon"] = $d["sicon"];
$row_array["perc"] = intval($d["perc"]);
$row_array["pvalue"] = intval($d["pvalue"]);
$row_array["vfixed"] = intval($d["vfixed"]);
$row_array["sectionValues"] = array();
array_push($row_array["sectionValues"],
intval($d["perc"]),
intval($d["id"]),
0
);
$row_array["sectionIndicators"] = array();
//loop indicators
if (!empty($indicators)) {
$i=-1;
foreach ($indicators as $v) {
if ($d["id"] == $v["idsec"]) {
$i++;
$row_array["sectionIndicators"][$i]["iid"] = intval($v["iid"]);
$row_array["sectionIndicators"][$i]["iname"] = $v["iname"];
$row_array["sectionIndicators"][$i]["perc"] = intval($v["perc"]);
$row_array["sectionIndicators"][$i]["pvalue"] = intval($v["pvalue"]);
$row_array["sectionIndicators"][$i]["vfixed"] = intval($v["vfixed"]);
$row_array["sectionIndicators"][$i]["finalArray"] = array();
array_push($row_array["sectionIndicators"][$i]["finalArray"],
intval($v["perc"]),
intval($d["id"]),
intval($v["iid"])
);
}
}
}
array_push($data, $row_array);
}
}

<?php
// Assumption that your array is like this :
$sections = [0 => ['id'=>1, 'sname'=>'Sname', 'sicon'=>'SIcon', 'perc'=>'Perc', 'pvalue'=>'Pvalue', 'vfixed'=>'Vfixed'], 1 => ['id'=>2, 'sname'=>'Sname2', 'sicon'=>'SIcon2', 'perc'=>'Perc2', 'pvalue'=>'Pvalue2', 'vfixed'=>'Vfixed2']];
$indicators = [ 0 => ['idsec'=>1, 'iid'=>1, 'iname'=>'viname', 'perc'=>'vperc', 'pvalue'=>'vpvalue', 'vfixed'=>'vVfixed'], 1 => ['idsec'=>2, 'iid'=>2, 'iname'=>'viname2', 'perc'=>'vperc2', 'pvalue'=>'vpvalue2', 'vfixed'=>'vVfixed2']];
// Initialisation your result array
$data = [];
if (!empty($sections)) {
foreach ($sections as $d) {
$row_array = array();
$row_array["id"] = intval($d["id"]);
$row_array["sname"] = $d["sname"];
$row_array["sicon"] = $d["sicon"];
$row_array["perc"] = intval($d["perc"]);
$row_array["pvalue"] = intval($d["pvalue"]);
$row_array["vfixed"] = intval($d["vfixed"]);
$row_array["sectionValues"] = array();
array_push($row_array["sectionValues"],
intval($d["perc"]),
intval($d["id"]),
0
);
//loop indicators
if (!empty($indicators)) {
foreach ($indicators as $v) {
if ($d['id'] == $v['idsec']) {
$row_array["sectionIndicators"] = array();
$row_array["sectionIndicators"][] = array(
"iid" => intval($v["iid"]),
"iname" => $v["iname"],
"perc" => intval($v["perc"]),
"pvalue" => intval($v["pvalue"]),
"vfixed" => intval($v["vfixed"])
);
$row_array["sectionIndicators"]["iid"] = intval($v["iid"]);
$row_array["sectionIndicators"]["iname"] = $v["iname"];
$row_array["sectionIndicators"]["perc"] = intval($v["perc"]);
$row_array["sectionIndicators"]["pvalue"] = intval($v["pvalue"]);
$row_array["sectionIndicators"]["vfixed"] = intval($v["vfixed"]);
$row_array["sectionIndicators"]["finalArray"] = array();
}
}
}
array_push($data, $row_array);
}
}
echo '<pre>';
print_r( $data );
Result :
Array
(
[0] => Array
(
[id] => 1
[sname] => Sname
[sicon] => SIcon
[perc] => 0
[pvalue] => 0
[vfixed] => 0
[sectionValues] => Array
(
[0] => 0
[1] => 1
[2] => 0
)
[sectionIndicators] => Array
(
[0] => Array
(
[iid] => 1
[iname] => viname
[perc] => 0
[pvalue] => 0
[vfixed] => 0
)
[iid] => 1
[iname] => viname
[perc] => 0
[pvalue] => 0
[vfixed] => 0
[finalArray] => Array
(
)
)
)
[1] => Array
(
[id] => 2
[sname] => Sname2
[sicon] => SIcon2
[perc] => 0
[pvalue] => 0
[vfixed] => 0
[sectionValues] => Array
(
[0] => 0
[1] => 2
[2] => 0
)
[sectionIndicators] => Array
(
[0] => Array
(
[iid] => 2
[iname] => viname2
[perc] => 0
[pvalue] => 0
[vfixed] => 0
)
[iid] => 2
[iname] => viname2
[perc] => 0
[pvalue] => 0
[vfixed] => 0
[finalArray] => Array
(
)
)
)
)

I found out that I had to give an index. My solution:
if (!empty($sections)) {
foreach ($sections as $d) {
$row_array = array();
$row_array["id"] = intval($d["id"]);
$row_array["sname"] = $d["sname"];
$row_array["sicon"] = $d["sicon"];
$row_array["perc"] = intval($d["perc"]);
$row_array["pvalue"] = intval($d["pvalue"]);
$row_array["vfixed"] = intval($d["vfixed"]);
$row_array["sectionValues"] = array();
array_push($row_array["sectionValues"],
intval($d["perc"]),
intval($d["id"]),
0
);
$row_array["sectionIndicators"] = array();
//loop indicators
if (!empty($indicators)) {
$i=-1;
foreach ($indicators as $v) {
if ($d["id"] == $v["idsec"]) {
$i++;
$row_array["sectionIndicators"][$i]["iid"] = intval($v["iid"]);
$row_array["sectionIndicators"][$i]["iname"] = $v["iname"];
$row_array["sectionIndicators"][$i]["perc"] = intval($v["perc"]);
$row_array["sectionIndicators"][$i]["pvalue"] = intval($v["pvalue"]);
$row_array["sectionIndicators"][$i]["vfixed"] = intval($v["vfixed"]);
$row_array["sectionIndicators"][$i]["finalArray"] = array();
array_push($row_array["sectionIndicators"][$i]["finalArray"],
intval($v["perc"]),
intval($d["id"]),
intval($v["iid"])
);
}
}
}
array_push($data, $row_array);
}
}

Related

Replace array key with part of value name

I have this format of array
[0] => Array
(
[0] => FieldType: Text
[1] => FieldName: Job title
[2] => FieldFlags: 0
[3] => FieldValue: ICT Manager
[4] => FieldJustification: Left
)
How can i make it look like
[0] => Array
(
[FieldType: ] => Text
[FieldName: ] => Job title
[FieldFlags: ] => 0
[FieldValue: ] => ICT Manager
[FieldJustification: ] => Left
)
Try like below:-
<?php
$array = Array
(
0 => Array
(
0 => 'FieldType: Text',
1 => 'FieldName: Job title',
2 => 'FieldFlags: 0',
3 => 'FieldValue: ICT Manager',
4 => 'FieldJustification: Left'
)
);
$new_array = array();
$i = 0;
foreach($array as $val){ // iterate through array
foreach($val as $k=> $v){ //for each index one array is there so iterate that also
$data = explode(':',$v); // explode the value by :
$new_array[$i][$data[0].":"] = $data[1]; // assign first value as key and second value as value to the new array
}
$i++;
}
echo "<pre/>";print_r($new_array); //print new array
?>
Output:- https://eval.in/394135
$result = array();
foreach ($input as $rows) {
$output = array();
foreach ($rows as $subRow) {
$values = explode(':', $subRow);
if (count($values) == 2) {
$output[$values[0] . ':'] = trim($values[1]);
}
}
$result[] = $output;
}
$array = array(
'0' => array(
'0' => 'FieldType: Text',
'1' => 'FieldName: Job title',
'2' => 'FieldFlags: 0',
'3' => 'FieldValue: ICT Manager',
'4' => 'FieldJustification: Left'
)
);
$nArray = array();
foreach($array as $k => $v){
foreach($v as $key => $value){
if(($pos = strpos($value, ':')) !== false){
$nArray[$k][substr($value, 0, $pos + 1)] = trim(substr($value, $pos + 1));
} else {
$nArray[$k][] = $value;
}
}
}
echo '<pre>';
print_r($nArray);

Merge two different array

I am confused with array.
What I want to do is two merge two array, but this kind of the two array are different:
Array
(
[0] => Array
(
[sud] => 60
[sad] => Array
(
[incharge] => Perusahaan
[perusahaan_id] => 1
[barang_id] => 3
[gudang_id] => 2
[stock] => 1
)
)
[1] => Array
(
[sud] => 23
[sad] => Array
(
[incharge] => Perusahaan
[perusahaan_id] => 1
[barang_id] => 4
[gudang_id] => 1
[stock] => 2
)
)
)
I want to move the array of [sud] into [sad] array, and named it as quantity.
This is my codes which generate the array above:
if($q->num_rows() > 0)
{
foreach ($q->result() as $row => $rows)
{
$data[] = $rows;
$stock[] = $rows->stock;
}
}
$i = -1;
foreach ($update as $updates)
{
$i++;
$test3['sud'] = $stock[$i];
$test3['sad'] = $updates;
$happy[] = $test3;
}
print_r ($happy);
What I want to do here actually is to check if the number of array [stock] => value is not bigger than the number in array [sud].
Please help, thanks in advance.
If I understood well, you want to change it like this:
if($q->num_rows() > 0)
{
foreach ($q->result() as $row => $rows)
{
$data[] = $rows;
$stock[] = $rows->stock;
}
}
$i = -1;
foreach ($update as $updates)
{
$i++;
$test3['sad'] = $updates;
$test3['sad']['quantity'] = $stock[$i];
$happy[] = $test3;
}
print_r ($happy);

Sort and group array from timestamp

I have the following array:
Array
(
[0] => Array
(
[dest_in_id] => 1
[dest_user_id] => 37251
[dest_inv_user_id] => 37247
[dest_timestamp] => 1387168510
[dest_destination_id] => 64
)
[1] => Array
(
[gi_in_id] => 3
[gi_user_id] => 37251
[gi_inv_user_id] => 14564
[gi_timestamp] => 1345220045
[gi_group_id] => 2
)
[2] => Array
(
[dest_in_id] => 2
[dest_user_id] => 37251
[dest_inv_user_id] => 37257
[dest_timestamp] => 1387168510
[dest_destination_id] => 64
)
[3] => Array
(
[gi_in_id] => 3
[gi_user_id] => 37251
[gi_inv_user_id] => 14564
[gi_timestamp] => 1345220045
[gi_group_id] => 2
)
)
Need to review the difference in Timestamp each array and if it <= day (86400), then create an array type:
Array
(
[1387168510] => Array
(
[0] => Array
(
[dest_in_id] => 1
[dest_user_id] => 37251
[dest_inv_user_id] => 37247
[dest_timestamp] => 1387168510
[dest_destination_id] => 64
)
[1] => Array
(
[dest_in_id] => 2
[dest_user_id] => 37251
[dest_inv_user_id] => 37257
[dest_timestamp] => 1387168510
[dest_destination_id] => 64
)
)
[1345220045] => Array
(
[0] => Array
(
[gi_in_id] => 3
[gi_user_id] => 37251
[gi_inv_user_id] => 14564
[gi_timestamp] => 1345220045
[gi_group_id] => 2
)
[1] => Array
(
[gi_in_id] => 3
[gi_user_id] => 37251
[gi_inv_user_id] => 14564
[gi_timestamp] => 1345220045
[gi_group_id] => 2
)
)
)
Important note! Keys may be different!
At once appealed to the function usort. Wanted to do something like this:
usort($aInvitesRows, function($a, $b) {
$akey = array_keys($a);
$bkey = array_keys($b);
if (($b[preg_grep("/(.*?)_timestamp/", $bkey)[3]] - $a[preg_grep("/(.*?)_timestamp/", $akey)[3]]) <= 86400) {
return $b[preg_grep("/(.*?)_timestamp/", $bkey)[3]] = array($a, $b);
}
});
Success of this venture was not crowned :(
At this stage, using usort could only sort by Timestamp (*), what do you do - do not know the, address for the help!
*
usort($aInvitesRows, function($a, $b) {
$akey = array_keys($a);
$bkey = array_keys($b);
return strcmp($b[preg_grep("/(.*?)_timestamp/", $bkey)[3]], $a[preg_grep("/(.*?)_timestamp/", $akey)[3]]);
});
function msort($array, $key, $sort_flags = SORT_REGULAR) {
if (is_array($array) && count($array) > 0) {
if (!empty($key)) {
$mapping = array();
foreach ($array as $k => $v) {
$sort_key = '';
if (!is_array($key)) {
$sort_key = $v[$key];
} else {
// #TODO This should be fixed, now it will be sorted as string
foreach ($key as $key_key) {
$sort_key .= $v[$key_key];
}
$sort_flags = SORT_STRING;
}
$mapping[$k] = $sort_key;
}
asort($mapping, $sort_flags);
$sorted = array();
foreach ($mapping as $k => $v) {
$sorted[] = $array[$k];
}
return $sorted;
}
}
return $array;
}
$arr = $aInvitesRows;
$result = array();
$item = array_shift($arr);
$akeys = array_keys($item);
$dt = new \DateTime();
$dt->setTimestamp($item[preg_grep("/(.*?)_timestamp/", $akeys)[3]]);
$dt->setTime(0, 0, 0);
$result[$dt->getTimestamp()] = array($item);
foreach ($arr as $item) {
$akeys = array_keys($item);
$f = false;
foreach ($result as $day => $items) {
$diff = ($item[preg_grep("/(.*?)_timestamp/", $akeys)[3]]) - $day;
if ($diff < 86400 && $diff > 0) {
$result[$day][] = $item;
$f = true;
break 1;
}
}
if (!$f) {
$dt = new \DateTime();
$dt->setTimestamp($item[preg_grep("/(.*?)_timestamp/", $akeys)[3]]);
$dt->setTime(0, 0, 0);
$result[$dt->getTimestamp()] = array($item);
}
}

How do i split this array into two?

I have this array.
Array
(
[name] => Array
(
[isRequired] => 1
[isBetween] => 1
[isAlphaLower] =>
[isLength] =>
)
[email] => Array
(
[isEmail] => 1
)
[pPhone] => Array
(
[isPhone] =>
)
)
i want to split the array into two.
1. array with all boolean value true
Array
(
[name] => Array
(
[isRequired] => 1
[isBetween] => 1
)
[email] => Array
(
[isEmail] => 1
)
)
2. array with all boolean value false
Array
(
[name] => Array
(
[isAlphaLower] =>
[isLength] =>
)
[pPhone] => Array
(
[isPhone] =>
)
)
How do i do it?
thank you..
initialize the two new arrays
foreach the input array
foreach the inner array of each input array entry
according to the value set the one or the other of the two new arrays
done.
Example:
$arrayTrue = $arrayFalse = arrray(); # 1
foreach($arrayInput as $baseKey => $inner) # 2
foreach($inner as $key => $value) # 3
if ($value) $arrayTrue[$basekey][$key] = $value; # 4
else $arrayFalse[$basekey][$key] = $value;
function is_true($var) {
return $var;
}
function is_false($var) {
return !$var;
}
$result_true = array();
$result_false = array();
foreach ($array as $k => $a) {
$result_true[$k] = array_filter($a, 'is_true');
$result_false[$k] = array_filter($a, 'is_false');
};
or
$result_true = array();
$result_false = array();
foreach ($array as $k => $a) {
$result_true[$k] = array_filter($a);
$result_false[$k] = array_filter($a, function ($x) { return !$x; } );
};
As your array is a 2 level array, you will need to use 2 loops.
$trueValues = array();
$falseValues = array();
foreach($input AS $key=>$firstLevelValue) {
foreach($firstLevelValue AS $key2=>$secondLevelValue) {
if ($secondLevelValue)
$trueValues[$key][$key2] = $secondLevelValue;
else
$falseValues[$key][$key2] = $secondLevelValue;
}
}
A 3 level array would be:
$trueValues = array();
$falseValues = array();
foreach($input AS $key=>$firstLevelValue) {
foreach($firstLevelValue AS $key2=>$secondLevelValue) {
foreach($secondLevelValue AS $key3=>$thirdLevelValue) {
if ($thirdLevelValue)
$trueValues[$key][$key2][$key3] = $thirdLevelValue;
else
$falseValues[$key][$key2][$key3] = $thirdLevelValue;
}
}
}

Counting an eliminating duplicate associative values in an array

I have the following issue, I have an array with the name $data
Within this array I have something like
[6] => Array
(
[code] => 642
[total] => 1708
)
[7] => Array
(
[code] => 642
[total] => 53
)
[8] => Array
(
[code] => 642
[total] => 1421
)
In some elements the code value is the same, now what I want to do is merge all the elements with the same code value together, and adding the totals together. I tried doing this in a foreach loop, but does not seem to work.
I do something like this
$old_lc = null;
$old_lcv = 0;
$count = 0;
$dd = null;
foreach($data as $d){
if($d['code'] == $old_lc){
$d['total'] = $d['total'] + $old_lcv;
$count--;
$dd[$count]['code'] = $d['code'];
$dd[$count]['total'] = $d['total'];
}else{
$dd[$count]['code'] = $d['code'];
$dd[$count]['total'] = $d['total'];
$count++;
}
$old_lc = $d['code'];
$old_lcv = $d['total'];
}
$data = $dd;
But this does not seem to work. Also I need the $data array to keep the keys, and should remain in the same format
$result = array();
foreach($ary as $elem) {
$code = $elem['code'];
$total = $elem['total'];
if(!isset($result[$code]))
$result[$code] = 0;
$result[$code] += $total;
}
This code translates the above array into an array of code => total.
$out = array();
foreach ($data as $k => $v) {
$out[$v['code']] += $v['total'];
}
It is worth noting that on certain settings this will generate a warning about undefined indexes. If this bothers you, you can use this alternate version:
$out = array();
foreach ($data as $k => $v) {
if (array_key_exists($v['code'], $out)) {
$out[$v['code']] += $v['total'];
} else {
$out[$v['code']] = $v['code'];
}
}
This turns it back into something like the original, if that's what you want:
$output = array();
foreach ($out as $code => $total) {
$output[] = array('code' => $code, 'total' => $total);
}
Note: the original keys of $data aren't maintained but it wasn't stated that this was a requirement. If it is, it needs to be specified how to reconstruct multiple elements that have the same code.
[6] => Array
(
[code] => 642
[total] => 1708
)
[7] => Array
(
[code] => 642
[total] => 53
)
[8] => Array
(
[code] => 642
[total] => 1421
)
$data_rec = array();
$data = array();
foreach($data_rec as $key=>$rec)
{
$data[$key]+= $rec[$key];
}
print_r($data);

Categories