How can I make a two dimensional array with the following example using for loop:
$test = array ('D','D','D','D','C','C','D','D');
output should be like this:
$output = array( 0 => array('D','D','D','D'), 1 => array('D','D'));
thanks for your help.
Here is my code:
$test = array('D','D','D','D', 'C','C','D', 'D');
$output = array();
$myarray = array();
for ($i= 0; $i < count($test); $i++){
if($test[$i] == 'D'){
array_push($myarray , $test[$i]);
} else {
array_push($output,$myarray);
}
}
//OUTPUT: $output = (array( 0 => array('D','D','D','D'), 1 => array('D','D','D','D'));
this can be implemented using only one foreach loop.
<?php
$test = array ('D','C','D','D','D','D','C','C','D','D','C','D');
$temp = array();
$result = array();
foreach($test as $value){
if($value != 'D' && !empty($temp)){
array_push($result, $temp);
$temp = array();
}
else{
array_push($temp, $value);
}
}
if(!empty($temp)){
array_push($result, $temp);
}
print_r($result);
Related
I'm inserting multiple data in table through loop on 2D array.
This is my data:
$data['id'] = array([0] => '1', [1] => '2');
$data['name'] = array([0] => 'Ben', [1] => 'Dan');
$data['status'] = array([0] => 'Active', [1] => 'Active');
$data['updatedby'] = '1';
$data['updateddate'] = date('d-M-y H:i');
$idColumn = 'id';
$table = 'tablename';
This is my code:
foreach($data as $key => $value){
$i = 0;
if($key <> 'updatedby' && $key <> 'updateddate'){
foreach($value as $row){
$result = $this->myModel->recordUpdate($idColumn, $data['id'][$i], array($key => $row), $table);
$i = $i + 1;
}
}
if($key == 'updatedby'){
foreach($data['id'] as $row){
$result = $this->myModel->recordUpdate($idColumn, $row, array($key => $data['updatedby']), $table);
}
}
if($key == 'updateddate'){
foreach($data['id'] as $row){
$result = $this->myModel->recordUpdate($idColumn, $row, array($key => $data['updateddate']), $table);
}
}
}
function recordUpdate($idColumn, $id, $data, $table)
{
$this->db->where($idColumn, $id);
$this->db->update($table, $data);
$update_id = $this->db->affected_rows();
return $update_id;
}
Is there any way to do main loop through rows first then column, I would like to make this code more shorter and reliable.
You can do it by filtering and transposing your main data first:
$rows = array_transpose(array_filter($data, function($key){
return !in_array($key, ["updatedby","updateddate"]);
}, ARRAY_FILTER_USE_KEY));
function array_transpose($array){
$keys = array_keys($array);
$new_array = [];
for($i = 0, $len = count($array[$keys[0]]); $i < $len; $i++){
$new_array[$i] = [];
foreach($keys as $key){
$new_array[$i][$key] = $array[$key][$i];
}
}
return $new_array;
}
Then you can loop over the rows like this:
for($row = 0, $cnt = count($rows); $row < $cnt; $row++){
$column_data = $rows[$row];
$column_keys = array_keys($column_data);
$column_id = $column_data[$idColumn];
foreach($column_keys as $key){
recordUpdate(
$idColumn,
$column_id,
[$key => $column_data[$key]],
$table
);
}
// set the updatedby and updateddate for each row
$this->myModel->recordUpdate($idColumn, $column_id, ["updatedby" => $data["updatedby"]], $table);
$this->myModel->recordUpdate($idColumn, $column_id, ["updateddate" => $data["updateddate"]], $table);
}
I have an array that looks like this:
$ratingsInPosts = array
(
array("1",3),
array("2",5),
array("2",2),
array("5",2),
array("90",1),
array("5",6),
array("2",2),
);
I Want to find duplicate values in the first column and avarage its values from the second column.
So that this("1",3),("2",5),("2",2),("5",2),("90",1),("5",6),("2",2)
ends up like this ("1",3),("2",3),("5",4),("90",1)
Try this tested solution
I got the required Output
$ratingsInPosts = array
(
array("1",3),
array("2",5),
array("2",2),
array("5",2),
array("90",1),
array("5",6),
array("2",2),
);
$arr1 = array_column($ratingsInPosts, 0);
$p = array_count_values($arr1);
foreach($p as $key => $value)
{
$sum = 0;
for($i=0; $i < $value; $i++)
{
$pos = array_search($key, $arr1);
$sum += $ratingsInPosts[$pos][1];
unset($arr1[$pos]);
unset($ratingsInPosts[$pos]);
}
$re[] = array('"'.$key.'"',$sum/$value);
}
print_r($re);
I hope it helps you:
$groups = array();
// in this loop we group values by first column
foreach ($ratingsInPosts as $row) {
$key = $row[0];
if (!isset($groups[$key]) {
$groups[$key] = array();
}
$groups[$key][] = $row[1];
}
$result = array();
foreach ($groups as $key => $value) {
$avg = array_sum($value) / count($value);
$row = array($key, $avg);
$result[] = $row;
}
<?php
header('Content-Type: text/plain');
$ratingsInPosts = array(array("1",3),array("2",5),array("2",2),array("5",2),array("90",1),array("5",6),array("2",2));
$result = array();
$output = array();
foreach($ratingsInPosts as $array){
$result[$array[0]][] = $array[1];
}
foreach($result as $key=>$array){
$output[] = array($key,round(array_sum($array)/count($array)));
}
var_export($output);
?>
I have some array like this how can i split the key and value in php ?
[A0E4NL014XVM273] => Array
(
[0] => qexixdb
)
[A0E4UK024XVM014_Clone] => Array
(
[0] => pe8w3100
[1] => pe8w3100
)
Tried Query
foreach($vm_array as $vmkey=> $vmvalue){
$varray[] = $vmvalue;
/*foreach($vmvalue as $vmvalue=> $vmvalufmarray){
$vm_array[$vmkey][] = $vmvalufmarray.',';
}*/
}
Expected Output
[A0E4UK024XVM014_Clone] => pe8w3100,pe8w3100
You need to make a function called implode().
foreach($vm_array as $vmkey=> $vmvalue){
$varray[$vmkey] = implode(",", $vmvalue);
}
print_r($varray);
Try using PHP's implode on the inner array;
foreach($vm_array as $vmkey => $vmvalue){
$vm_array[$vmkey] = implode(",", $vmvalue);
}
I tried your example and simulated my own, if my understanding is right, if you want to retain them in the array.
$test = array("[A0E4NL014XVM273]" => array("qexixdb"),"[A0E4UK024XVM014_Clone]" => array("pe8w3100","pe8w3100"));
echo "<pre>";
var_dump($test);
echo "</pre>";
$new_arr_ = array();
foreach($test as $id => $value) {
$new_val = "";
for($i = 0, $ctr_val = count($value); $i < $ctr_val; $i++) {
$old_id = "";
if($id != $old_id) {
if($i < ($ctr_val - 1)) {
$new_val .= $value[$i] . ",";
} else {
$new_val .= $value[$i];
}
$old_id = $id;
}
}
$new_arr_[] = array($id => $new_val);
}
echo "<pre>";
var_dump($new_arr_);
echo "</pre>";
Or if just one array:
$new_arr_ = array();
foreach($test as $key=> $value){
$new_arr_[key] = implode(",", $value);
}
echo "<pre>";
var_dump($new_arr_);
echo "</pre>";
Hope it helps.
I have a comma separated string like
$str = "word1,word2,word3";
And i want to make a parent child relationship array from it.
Here is an example:
Try this simply making own function as
$str = "word1,word2,word3";
$res = [];
function makeNested($arr) {
if(count($arr)<2)
return $arr;
$key = array_shift($arr);
return array($key => makeNested($arr));
}
print_r(makeNested(explode(',', $str)));
Demo
function tooLazyToCode($string)
{
$structure = null;
foreach (array_reverse(explode(',', $string)) as $part) {
$structure = ($structure == null) ? $part : array($part => $structure);
}
return $structure;
}
Please check below code it will take half of the time of the above answers:
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
$result = array($arr[$i] => $result);
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';
Here is another code for you, it will give you result as you have asked :
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
if($i == 0){
$result = array($arr[$i] => $result);
}else{
$result = array(array($arr[$i] => $result));
}
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';
is there a simple way to access the nth element in a multidimensional array in php?
so for example
$arr = array(
[0] => array(1,4,7,3,53),
[6] => array(6,3,9,12,51,7),
[2] => array(9,94,54,3,87));
the 12th element would be 9.
array keys are not necessarily in order, nor each array row is of the same length.
Try this :
<?php
$arr = array(
'0'=> array(1,4,7,3,53),
'6'=>array(6,3,9,12,51,7),
'2'=>array(9,94,54,3,87)
);
$newArray=array();
foreach($arr as $array){
$newArray=array_merge($newArray, $array);
}
echo $newArray[11];
?>
untested, should work...
$arr = array(
0 => array(1,4,7,3,53), // your code was wrong here
6 => array(6,3,9,12,51,7),
2 => array(9,94,54,3,87));
function getnth ($array, $offset) {
$tmp_arr = array();
foreach ($array as $key => $value) {
foreach ($value as $val) {
$tmp_arr[] = $val;
}
}
return (isset($tmp_arr[$offset -1]) ? $tmp_arr[$offset -1] : FALSE);
}
getnth($arr, 12);
Edit: got to admit, the array_merge version is better....
Edit2: this is probably faster, if performance is an issue....
function getnth($array, $offset) {
$i = 0;
foreach ($array as $key => $value){
$size = count($value);
$i += $size;
if($offset <= $i) {
$new_off = $size - ($i - $offset) -1 ;
return $value[$new_off];
}
}
return FALSE;
}
function get_item($arr, $path, $delim = '.') {
$path = explode($delim, $path);
$result = $arr;
foreach ($path as $item) {
if (isset($result[$item])) {
$result = $result[$item];
} else {
return null;
}
}
return $result;
}
using:
echo get_item($arr, 'item.value.3.4.2.etc');