Related
I am trying to insert batch query in code igniter, I am not able to make array_merge work. Don't know whats the problem. M getting blank array.
$epin_amt = $this->input->post('amount');
$qty = $this->input->post('qty');
$data = array();
for ($i = 0; $i <= $qty; $i++) {
$array = array(
'epin' => mt_rand(100000, 999999),
'amount' => $epin_amt,
);
array_merge($data, $array);
}
print_r($data) ; // Produce : array( )
You have to assign the merged array back to your $data variable:
<?php
$epin_amt = /*$this->input->post('amount')*/ 5;
$qty = /*$this->input->post('qty')*/6;
$data = array();
for ($i = 0; $i <= $qty; $i++) {
$array = array(
'epin' => mt_rand(100000, 999999),
'amount' => $epin_amt,
);
$data = array_merge($data, $array);
}
print_r($data) ;
array_merge returns array. You need something like this:
$result = array_merge($data, $array);
You are merging the arrays but it's not done by reference so you're throwing the resulting array away. array_push() it instead, that will keep adding the arrays to your $data array:
<?php
$epin_amt = 10;
$qty = 20;
$data = array();
for ($i = 0; $i <= $qty; $i++) {
$array = array(
'epin' => mt_rand(100000, 999999),
'amount' => $epin_amt,
);
array_push($data, $array);
}
print_r($data) ;
I have a string:
$content = "test,something,other,things,data,example";
I want to create an array where the first item is the key and the second one the value.
It should look like this:
Array
(
[test] => something
[other] => things
[data] => example
)
How can I do that? It's difficult to search for a solution because I don't know how to search this.
It's very similar to this: Explode string into array with key and value
But I don't have a json array.
I tried something like that:
$content = "test,something,other,things,data,example";
$arr = explode(',', $content);
$counter = 1;
$result = array();
foreach($arr as $item) {
if($counter % 2 == 0) {
$result[$temp] = $item;
unset($temp);
$counter++;
} else {
$temp = $item;
$counter++;
continue;
}
}
print_r($result);
But it's a dirty solution. Is there any better way?
Try this:
$array = explode(',',$content);
$size = count($array);
for($i=0; $i<$size; $i++)
$result[$array[$i]] = $array[++$i];
Try this:
$content = "test,something,other,things,data,example";
$data = explode(",", $content);// Split the string into an array
$result = Array();
$size = count($data); // Calculate the size once for later use
if($size%2 == 0)// check if we have even number of items(we have pairs)
for($i = 0; $i<$size;$i=$i+2){// Use calculated size here, because value is evaluated on every iteration
$result[$data[$i]] = $data[$i+1];
}
var_dump($result);
Try this
$content = "test,something,other,things,data,example";
$firstArray = explode(',',$content);
print_r($firstArray);
$final = array();
for($i=0; $i<count($firstArray); $i++)
{
if($i % 2 == 0)
{
$final[$firstArray[$i]] = $firstArray[$i+1];
}
}
print_r($final);
$content = "test,something,other,things,data,example";
$x = explode(',', $content);
$z = array();
for ($i=0 ; $i<count($x); $i+=2){
$res[$x[$i]] = $x[$i+1];
$z=array_merge($z,$res);
}
print_r($z);
I have tried this example this is working file.
Code:-
<?php
$string = "test,something|other,things|data,example";
$finalArray = array();
$asArr = explode( '|', $string );
foreach( $asArr as $val ){
$tmp = explode( ',', $val );
$finalArray[ $tmp[0] ] = $tmp[1];
}
echo "After Sorting".'<pre>';
print_r( $finalArray );
echo '</pre>';
?>
Output:-
Array
(
[test] => something
[other] => things
[data] => example
)
For your reference check this Click Here
Hope this helps.
You could able to use the following:
$key_pair = array();
$arr = explode(',', $content);
$arr_length = count($arr);
if($arr_length%2 == 0)
{
for($i = 0; $i < $arr_length; $i = $i+2)
{
$key_pair[$arr[$i]] = $arr[$i+1];
}
}
print_r($key_pair);
$content = "test,something,other,things,data,example";
$contentArray = explode(',',$content);
for($i=0; $i<count($contentArray); $i++){
$contentResult[$contentArray[$i]] = $contentArray[++$i];
}
print_r( $contentResult);
Output
Array
(
[test] => something
[other] => things
[data] => example
)
$contentResult[$contentArray[1]] = $contentArray[2];
$contentResult[$contentArray[3]] = $contentArray[4];
$contentResult[$contentArray[5]] = $contentArray[6];
pretty sure my title needs to be fixed but anyhow, i have this loop. background info, i have 36 input "types" that need to be inserted 1 by 1. if the value has something.. set to a variable, if not set it to NULL.
MY question is, is there a loop i can perform to do this without listing 36 of these things.
using php version 5.2.17
if (!empty($_POST['type1'])){
$type1 = $_POST['type1'];
}
else
$type1 = NULL;
if (!empty($_POST['type2'])){
$type2 = $_POST['type2'];
}
else
$type2 = NULL;
if (!empty($_POST['type3'])){
$type3 = $_POST['type3'];
}
else
$type3 = NULL; // to 36...
php/html
<?php
for ($i = 1; $i < 37; $i++){
echo "Type$i:<input name='type$i' type='text' size='20' maxlength='35' /><br />";
}
?>
edit: I don't want to use an array.
To actually define all those variables $type1, $type2 etc, use "variable variables":
for ($i = 1; $i < 37; $i++) {
$varname = "type$i";
if (! empty($_POST[$varname])) {
$$varname = $_POST[$varname];
}
else {
$$varname = NULL;
}
}
Others suggest using an array instead (and in principle I agree), but this is an actual answer to the question.
Question was updated to not use an array. Will keep it here for someone looking for an answer that can use an array.
You could add the $_POST array to a predefined array of values storing the result in another array. For example:
<?php
$defaults = array(
"type1" => NULL,
"type2" => NULL,
"type3" => NULL,
"type4" => NULL
// etc
);
$_POST = array(
"type1" => 1,
"type2" => "foo"
);
$types = $_POST + $defaults;
print_r($types);
Which results in the array:
Array
(
[type1] => 1
[type2] => foo
[type3] =>
[type4] =>
...
)
Then for your html loop:
for ($i = 1; $i < 37; $i++){
echo "Type$i:<input name='" . $types["type" . $i] . "' type='text' size='20' maxlength='35' /><br />\n";
}
It is important to note that this is slightly different than using a check with empty.
Use an array on both the php and form inputs.
$type = array();
for ($i = 1; $i <= 36; $i++) {
if (isset($_POST['type'][$i])){
$type[$i] = $_POST['type'][$i];
}
}
HTML/PHP
<?php
for ($i = 1; $i <= 36; $i++){
echo "Type$i:<input name='type[$i]' type='text' size='20' maxlength='35' /><br />";
}
?>
Just an example with an array named $post.
$post = array(
'type1' => 'one',
'name' => 'test',
'type3' => 'three'
);
$matches = preg_grep ('^type[0-9]^', array_keys($post));
foreach ($matches as $val) {
$$val = $post[$val];
}
var_export($type1);
Use array for this
$i = 0;
$myinputs = 36;
while($i<$myinputs){
$i++;
if(empty($_POST['type'.$i.''])){
$type[$i] = $_POST['type'.$i.''];
}else{
$type[$i] = null;
}
}
print_r($type);
As the title states I'm searching for a unique solution in multi arrays. PHP is not my world so I can't make up a good and fast solution.
I basically get this from the database: http://pastebin.com/vYhFCuYw .
I want to check on the 'id' key, and if the array contains a duplicate 'id', then the 'aantal' should be added to each other.
So basically the output has to be this: http://pastebin.com/0TXRrwLs .
Thanks in advance!
EDIT
As asked, attempt 1 out of many:
function checkDuplicates($array) {
$temp = array();
foreach($array as $k) {
foreach ($array as $v) {
$t_id = $k['id'];
$t_naam = $k['naam'];
$t_percentage = $k['percentage'];
$t_aantal = $k['aantal'];
if ($k['id'] == $v['id']) {
$t_aantal += $k['aantal'];
array_push($temp, array(
'id' => $t_id,
'naam' => $t_naam,
'percentage' => $t_percentage,
'aantal' => $t_aantal,
)
);
}
}
}
return $temp;
}
How about this code, each 'aantal' has initial value of 1, and duplicated id have their aantal incremented mutually, and duplicated id's are not suppressed. As your first array index is 0-based numeric, so we don't consider this dimension as a hash array, but rather a normal array.
UPDATED: id's can be duplicated 2 times, 3 times, 4 times, ...
<?php
//
// duplicate elements are not suppressed:
//
function checkDuplicates($xarr) {
//
$xarrDone = array();
//
$n = count($xarr);
//
for($i = 0; $i < $n; $i++)
{
if(! isset($xarrDone[$i]))
{
$id0 = $xarr[$i]['id'];
$hasId0 = array();
for($j = $i + 1; $j < $n; $j++)
{
if($xarr[$j]['id'] == $id0)
{
$hasId0[] = $j;
}
}
$n1 = count($hasId0);
if($n1 > 0)
{
$xarr[$i]['aantal'] += $n1;
$xarrDone[$i] = true;
for($j = 0; $j < $n1; $j++)
{
$xarr[$hasId0[$j]]['aantal'] += $n1;
$xarrDone[$hasId0[$j]] = true;
}
}
}
}
//
return $xarr;
}
//
// duplicate elements are suppressed:
//
function checkDuplicates2Unique($xarr) {
//
$xarrDone = array();
$xarrNew = array();
//
$n = count($xarr);
//
for($i = 0; $i < $n; $i++)
{
if(! isset($xarrDone[$i]))
{
$id0 = $xarr[$i]['id'];
$hasId0 = array();
for($j = $i + 1; $j < $n; $j++)
{
if($xarr[$j]['id'] == $id0)
{
$hasId0[] = $j;
}
}
$n1 = count($hasId0);
if($n1 > 0)
{
$xarr[$i]['aantal'] += $n1;
for($j = 0; $j < $n1; $j++)
{
$xarrDone[$hasId0[$j]] = true;
}
}
$xarrNew[] = $xarr[$i];
$xarrDone[$i] = true;
}
}
//
return $xarrNew;
}
//
// main test:
//
$xarr0 = array(
array(
'id' => 6
, 'naam' => 'Aardmonnik'
, 'percentage' => '8,00%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => 'Achel 8 Bruin'
, 'percentage' => '8,00%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => 'Achel ppBruin'
, 'percentage' => '9,00%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => 'Achel ppBruin'
, 'percentage' => '9,00%'
, 'aantal' => 1
)
, array(
'id' => 3
, 'naam' => 'IV Saison'
, 'percentage' => '6,5%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => '3 Schténg'
, 'percentage' => '6,00%'
, 'aantal' => 1
)
);
//
echo "<pre>
Original:
";
print_r($xarr0);
//
echo "</pre>";
//
$xarr = checkDuplicates($xarr0);
//
echo "<pre>
Modified:
";
print_r($xarr);
//
$xarr = checkDuplicates2Unique($xarr0);
//
echo "<pre>
Modified Unique:
";
print_r($xarr);
//
echo "</pre>";
?>
?
checkDuplicates(): keep duplicated id's.
checkDuplicates2Unique(): delete duplicated id's to get unique id's.
Try using php's array_unique function: http://php.net/manual/en/function.array-unique.php
It should work on arrays
Otherwise (if you can sort the array -> faster):
<?php
$db = array(....); // your data
function remove_duplicates (array $arr) {
usort($arr, function ($a, $b) {
return $a['id'] < $b['id'];
});
$result = array();
$last_id = null;
$last_index = -1;
for ($i=0; $i<count($arr); ++$i) {
if ($arr[$i]['id'] == $last_id) {
result[$last_index]['aantai'] += 1;
continue;
}
$last_id = $arr[$i]['id'];
$last_index = count($result);
$result[] = $arr[$i];
}
return $result;
}
?>
Only loop over the input once, then copy the element when the id is new, else add the value:
function checkDuplicates($array) {
$temp = array();
// Only loop through the input once
foreach($array as $k) {
// Use the id as array index
if (array_key_exists($k['id'], $temp) {
// Only check id and add aantal?
$temp[$k['id']['aantal'] += $k['aantal'];
} else {
// Copy the element to the output
$temp[$k['id']] = $k;
}
}
return $temp;
}
Depending on your further code, you might need to reset the array indices by sort() or something.
Edit: sorry I forgot an index to $temp - the aantal field schould be correct now.
From the queried database, we got this
foreach ($child_posts as $child_post) {
$child_id = $child_post->ID;
$dayOfWeek = get_post_meta($child_id,'wpcf-day-of-week', true);
$time = get_post_meta($child_id,'wpcf-time', true);
$class[] = array('day' => $dayOfWeek, 'time' => $time, 'value' => $child_id);
}
{"classes":[
{"day":"7","time":"1500","value":13574},
{"day":"7","time":"1800","value":13573},
{"day":"4","time":"1900","value":11346},
{"day":"6","time":"1100","value":11494},
{"day":"5","time":"1800","value":11362},
{"day":"7","time":"1700","value":13572},
{"day":"6","time":"1600","value":11498},
{"day":"6","time":"1500","value":11496}]}
Day = Mon - Sun
Time = Military time
Value = something I need, but do not need sorting
I need to sort first by day, then by time. And get back the database in the format like how it was
{"classes":[
{"day":"4","time":"1900","value":11346},
{"day":"5","time":"1800","value":11362},
{"day":"6","time":"1100","value":11494},
{"day":"6","time":"1500","value":11496},
{"day":"6","time":"1600","value":11498},
{"day":"7","time":"1500","value":13574},
{"day":"7","time":"1700","value":13572},
{"day":"7","time":"1800","value":13573}]}
I tried using the method in the php manual but I still can't really get it.
This is what I did
foreach ($class as $key => $row) {
$day[$key] = $row['day'];
$time[$key] = $row['time'];
$value[$key] = $row['value'];
}
$class[] = array_multisort($day, SORT_DESC, $time, SORT_ASC, $class);
I'm know what I should expect, but I don't know how to go around getting it. Hopefully someone can help out here :)
My orignial script:
$childargs = array(
'post_type' => 'class',
'numberposts' => -1,
'meta_query' => array(array('key' => '_wpcf_belongs_instructor_id', 'value' => $instructor_post_id))
);
$child_posts = get_posts($childargs);
//$child_posts = types_child_posts(‘class’);
foreach ($child_posts as $child_post) {
$child_id = $child_post->ID;
$dayOfWeek = get_post_meta($child_id,'wpcf-day-of-week', true);
$time = get_post_meta($child_id,'wpcf-time', true);
$class[] = array('day' => $dayOfWeek, 'time' => $time, 'value' => $child_id);
}
echo json_encode(
array("classes" => $class)
)
?>
<?php
$json = '{"classes":[
{"day":"7","time":"1500","value":13574},
{"day":"7","time":"1800","value":13573},
{"day":"4","time":"1900","value":11346},
{"day":"6","time":"1100","value":11494},
{"day":"5","time":"1800","value":11362},
{"day":"7","time":"1700","value":13572},
{"day":"6","time":"1600","value":11498},
{"day":"6","time":"1500","value":11496}]}';
$array = json_decode($json,true);
$temp = $array['classes'];
foreach($temp as $key=>$value)
{
$day[] = $value['day'];
$time[] = $value['time'];
}
array_multisort($day,SORT_ASC,$time,SORT_ASC,$temp);
$array['classes'] = $temp;
echo json_encode($array);
?>
try changing your code to .I assume that $classes contains the json_decoded content.
$temp = $classes['classes'];
foreach ($temp as $key => $row) {
$day[] = $row['day'];
$time[] = $row['time'];
$value[] = $row['value'];
}
array_multisort($day, SORT_DESC, $time, SORT_ASC, $temp);
$classes['classes'] = $temp;
echo json_encode($classes);
To sort an array of rows returned from MYSql by one column.
The problem here is to sort courses by session (1,2) and period (1,2,3) If the session = 3 it means both so in preparing the table for sorting and printing if session == 3 then insert a row 1, and a row 2. Then do the sort. The table contents are in $coursesr.
$ar = array();
if ($order == "session"){
for ($i = 0; $i < count($coursesr); $i++){
$ar[0][] = (($coursesr[$i]['session'])*10)+$coursesr[$i]['period'];
$ar[1][] = $i;
}
$b = array_multisort($ar[0],SORT_ASC,SORT_NUMERIC,$ar[1],SORT_ASC,SORT_NUMERIC);
}else{
for ($i = 0; $i < count($coursesr); $i++){
$ar[0][] = ucwords($coursesr[$i]['lastname']);
$ar[1][] = $i;
}
array_multisort($ar[0],SORT_ASC,SORT_NATURAL,$ar[1],SORT_ASC,SORT_NUMERIC);
}
Then to get it out of the $coursesr array you have to compute the index...
for ($i = 0; $i < $num; $i++){
$r = $coursesr[$ar[1][$i]]; // simplify reference
echo "<tr>";.....