How can i change the test1 array format as like in test2?
$test1 = array(
'size'=>array('V'=>array('V'),'R'=>array('R','R')),
'price'=>array('V'=>array('77'),'R'=>array('88','99')),
'unit'=>array('V'=>array('3'),'R'=>array('3','2')),
'color'=>array('V'=>array('Black'),'R'=>array('Green','Red')));
$test2 = array(
'size'=>array('V','R'),
'price'=>array('V'=>array('Black'=>'77'),
'R'=>array('Green'=>'88','Red'=>'99')),
'unit'=>array('V'=>array('Black'=>'3'),
'R'=>array('Green'=>'3','Red'=>'2')),
'color'=>array('V'=>array('Black'),'R'=>array('Green','Red')));
Thanks!
With a foreach loop you can change the array structure.
http://php.net/manual/de/control-structures.foreach.php
Something like that should work: its pretty unclear what the rules are to convert from one array to the other in your case.
$test2 = array();
foreach ($test as $type => $array) {
$newArray = array();
foreach ($array as $key => $value) {
if ($key == 'V') {
if ($value == 3) {
$newArray['V'] = array('Black' => 3);
} else if ($value = 2) {
$newArray['V'] = array('Green' => 2);
}
} else if ($key == 'R') {
//....
}
}
$test2[$type] = $newArray;
}
Thanks for the response. and sorry for not being more specific. Actually i wanted all the values in dynamic manner. I constructed a loop :). Thanks!
$myArray = array();
foreach($test as $type => $array){
$k = 0;
foreach ($array as $key => $value) {
if($type == 'size'){
$myArray['size'][] = $key;
}else if($type == 'price' || $type == 'unit' ){
$m = 0;
foreach($value as $vall){
if($type == 'price'){
$myArray['price'][$myArray['size'][$k]][$test['color'][$myArray['size'][$k]][$m]] = $test['price'][$myArray['size'][$k]][$m];
}else if($type == 'unit'){
$myArray['unit'][$myArray['size'][$k]][$test['color'][$myArray['size'][$k]][$m]] = $test['unit'][$myArray['size'][$k]][$m];
}
$m++;
}
}else if($type == 'color'){
$myArray['color'][] = $value;
}
$k++;
}
}
Related
I'm trying to merge multiple arrays with same keys and add their values if keys exist, if not add a new object. Could not get the logic right on this
these are samle arrays
[{"2":"90"},{"12":"400"},{"25":"750"},{"0":"50"}]
[{"1":"100"},{"23":"200"},{"12":"1000"},{"0":"5"}]
and the expected output is
[{ {"2":"90"},{"12":"1400"},{"25":"750"},{"0":"55"},{"1":"100"},{"23":"200"}]
This is php code i have used
while($row = $result->fetch_assoc())
{
if ($i==0)
{
$rowOut = $row;
$i++;
}else
{
foreach($rowOut as $key1 => $value1) {
foreach($row as $key => $value)
{
if($key == $key1){
(int)$rowOut->$value1 = (int)$value + (int)$value1;
}
}
}
}
}
not the most elegant solution, but it works
$a = [2=>90,12=>400,25=>750,0=>50] ;
$b = [1=>100,23=>200,12=>1000,0=>5];
$ak = array_keys($a);
$bk = array_keys($b);
$ck = array_intersect($ak,$bk);
$out = [];
foreach ($ck as $key => $value)
{
$out[$value] = $a[$value] + $b[$value];
unset($a[$value]);
unset($b[$value]);
}
foreach ($a as $key => $value)
{
$out[$key] = $value;
}
foreach ($b as $key => $value)
{
$out[$key] = $value;
}
var_dump($out);
You may concat the two arrays and use reduce to construct the new array.
demo
<?php
$array1 = [
["2" => "90"],
["12" => "400"],
["25" => "750"],
["0" => "50"]
];
$array2 = [
["1" => "100"],
["23" => "200"],
["12" => "1000"],
["0" => "5"]
];
$concat = [...$array1, ...$array2];
$reduce = array_reduce($concat, function ($carry, $item) {
$key = array_keys($item)[0];
if (isset($carry[$key])) {
$carry[$key][$key] += $item[$key];
} else {
$carry[$key] = [$key => $item[$key]];
}
$carry[$key][$key] = (string)$carry[$key][$key];
return $carry;
}, []);
$output = array_values($reduce);
echo var_dump($output);
I have function:
function funct($xls){
include_once '../system/PHPExcel/Classes/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load($xls);
$objPHPExcel->setActiveSheetIndex(9);
$aSheet = $objPHPExcel->getActiveSheet();
$array = array();
foreach($aSheet->getRowIterator() as $row){
$cellIterator = $row->getCellIterator();
//this array will contain arrays with cells values
$item = array();
foreach($cellIterator as $key => $cell){
//skip adding tables which we don't need
if($key == "A" || $key == "E" || $key == "F" || $key == "G" || $key == 'H') continue;
array_push($item, $cell->getCalculatedValue());
}
array_push($array, $item);
}
return $array;
}
How can I use the following code?
$this->mergedCellsRange = $this->activeSheet->getMergeCells();
foreach($this->mergedCellsRange as $currMergedRange) {
if($cell->isInRange($currMergedRange)) {
$currMergedCellsArray = PHPExcel_Cell::splitRange($currMergedRange);
$cell = $this->activeSheet->getCell($currMergedCellsArray[0][0]);
break;
}
}
For work with merged cells inside my code.
Currently my function add value only for first cell, and all an others is empty.
Thank you.
Found an answer for my issue:
function funct($xls){
include_once '../system/PHPExcel/Classes/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load($xls);
$objPHPExcel->setActiveSheetIndex(9);
$aSheet = $objPHPExcel->getActiveSheet();
$array = array();
foreach($aSheet->getRowIterator() as $row){
$cellIterator = $row->getCellIterator();
//this array will contain arrays with cells values
$item = array();
foreach($cellIterator as $key => $cell){
//merged cells echo start
foreach ($aSheet->getMergeCells() as $cells) {
if ($cell->isInRange($cells)) {
$currMergedCellsArray = PHPExcel_Cell::splitRange($cells);
$cell = $aSheet->getCell($currMergedCellsArray[0][0]);
echo $cells,'\n';
echo '';
break;
}
}
//merged cells echo end
//skip adding tables which we don't need
if($key == "A" || $key == "E" || $key == "F" || $key == "G" || $key == 'H') continue;
array_push($item, $cell->getCalculatedValue());
}
array_push($array, $item);
}
return $array;
}
I would like to insert an item after a specific pattern. In my case I would like to insert x after every second a in an array. After six'th a my code does not work properly:
$array = array("a","a","a","a","a","a","b","a","a");
$out = array();
foreach ($array as $key=>$value){
$out[] = $value; // add current letter to new array
if($value=='a' && $array[$key-1]=='a' && $out[$key] !='x'){ // check if current and last letter are a
$out[] = 'x'; // if so add an x to the array
}
}
print_r($out);
Correct answer at the end
Is it that what are you looking for?
<?php
$array = array("a","a","a","a","a","a","b","a","a");
foreach ($array as $key => $value){
if ($key == 0 || $key == 1) {
$array[$key] = $value;
} elseif($array[$key-1] == 'a' && $array[$key-2] == 'a' && $array[$key] == 'a') {
$array[$key] = 'x';
} else {
$array[$key] = $value;
}
}
$count = count($array);
if ($array[$count-1] == 'a' && $array[$count-2] == 'a') {
$array[] = 'x';
}
print_r($array);
?>
If I understand correctly, after 2 a you want to put x into new array.
UPDATE
Please check now. There will be added a new element x if last two are a in array.
With exceptions, but still working:
<?php
$array = array("a","a","a","a","a","a","b","a","a");
foreach ($array as $key => $value){
if($array[$key-1] == 'a' && $array[$key-2] == 'a' && $array[$key] == 'a') {
$array[$key] = 'x';
}
}
$count = count($array);
if ($array[$count-1] == 'a' && $array[$count-2] == 'a') {
$array[] = 'x';
}
print_r($array);
?>
UPDATE - Correct code
I think code below will fit all your needs:
<?php
$arr = array("a","w","a","d","a","a","b","a","a", "w");
$arr_count = count($arr);
for ($i = 0; $i < $arr_count; $i++){
if (!empty($arr[$i+1]) && $arr[$i] == $arr[$i+1]) {
$first_half = array_slice($arr, 0, $i+2);
$second_half = array_slice($arr, $i+2, $arr_count);
if (count($second_half) > 0) {
$arr = array_merge($first_half, ["x"], $second_half);
}
}
}
$count = count($arr);
if ($arr[$count-1] == 'a' && $arr[$count-2] == 'a') {
$arr[] = 'x';
}
print_r($arr);
?>
As it was mentioned in the comment, you sure can use regular expression in this particular situation:
$pattern = '/a{2}/';
$replacement = '$0x';
$out = str_split(preg_replace(
$pattern,
$replacement,
implode('', $array)
));
Basically, we gluing the characters together (using implode) to form the string and then replacing every "aa" with "aax". After that we split string back to the array using str_split.
Here is demo.
I have been going around in circles with a multidimensional array replace..
I need to replace numbers stored in a DB that relate to a status type.. If I did this in the view it would work but it wont seem to replace in the model?
function fetch_shipments($orgID){
$this->db->select('shipID, shipRef, shipCarrier, shipOrigin, shipDestination, shipQty, shipStatus');
$this->db->where('orgID', $orgID);
$query = $this->db->get('shipments');
$result = $query->result_array();
foreach($result as $row) {
foreach ($row as $key => $val) {
$key == 'shipStatus' && $val == 0 ? $val = 'Current' : $val;
$key == 'shipStatus' && $val == 1 ? $val = 'Pending' : $val;
$key == 'shipStatus' && $val == 2 ? $val = 'Complete' : $val;
}
}
return $result;
}
Has really left me scratching my head, I know this kind of foreach works as I use it all the time... I feel I am missing something (perhaps obvious) but I just cant put my finger on it. I even tried doing the replace at the object level before outputting an array but couldn't get that to work either.
you should save it on your $result variable. not in $val
foreach($result as $k => $row) {
foreach ($row as $key => $val) {
$key == 'shipStatus' && $val == 0 ? $result[$k][$key] = 'Current' : $val;
$key == 'shipStatus' && $val == 1 ? $result[$k][$key] = 'Pending' : $val;
$key == 'shipStatus' && $val == 2 ? $result[$k][$key] = 'Complete' : $val;
}
}
return $result;
Or you could remove the inner loop
foreach($result as $k => $row) {
if($row['shipStatus']==0){
$result[$k]['shipStatus'] = 'Current';
}elseif($row['shipStatus']==1){
$result[$k]['shipStatus'] = 'Pending';
}else{
$result[$k]['shipStatus'] = 'Complete';
}
}
return $result;
I believe placing a & before your loop variable should solve your problem, as then the reference would get updated.
So your loop would start something like this
foreach($result as &$row) {
foreach ($row as $key => &$val) {
What am I doing wrong here? It's so simple and I'm overlooking something. I'm trying to replace the value of an array key within a foreach loop:
$arr = array();
$arr['firstimg'] = '123';
$arr['secondimg'] = '456';
$arr['thirdimg'] = '789';
foreach ($arr as $key => $value) {
if ($key == 'secondimg') {
$value = '000';
}
}
print_r($arr);
The array is staying the same.
The variable $value is scoped to the loop. You need to update the value of $arr[$key].
Alternatively you can declare the loop as follows:
foreach ($arr as $key => &$value) {
This makes $value a reference to the original array value (rather than a copy).
Should Be :
foreach ($arr as $key => $value) {
if ($key == 'secondimg') {
$arr['secondimg'] = '000';
}
}
pass by refrence,
$arr = array();
$arr['firstimg'] = '123';
$arr['secondimg'] = '456';
$arr['thirdimg'] = '789';
foreach ($arr as $key => $value) {
if ($key == 'secondimg') {
$value = '000';
}
}
print_r($arr);
to
$arr = array();
$arr['firstimg'] = '123';
$arr['secondimg'] = '456';
$arr['thirdimg'] = '789';
foreach ($arr as $key => &$value) {
if ($key == 'secondimg') {
$value = '000';
}
}
print_r($arr);