Pushing an Array element into an existing multidimensional array in codeigniter - php

I have a query in codeigniter like this
$query_tutors = $this->db->get_where("tutor_info", array('tutor_id' => $tutor_id));
I have also other array elements that I want to pass in the query which depends on some conditions.
So how do I push other multidimensional array elements to the existing array so I can pass the variable as a whole in the query?
array_push is not working in this case.
$array = array();
$array = array("tutor_id" => $tutor_id);
$array = array("online" => $online); // want to merge this to the 1st array.
$query_tutors = $this->db->get_where("tutor_info", $array);

First you're doing it wrong.
$array = array();
$array = array("tutor_id" => $tutor_id);
You're recreating the array again, which will delete it from the memory. Either you have to use
$array['tutor_id'] = $tutor_id;
$array["online"] = $online;
or
$array = array('tutor_id' => $tutor_id, 'online' => $online);
or if you want to merge two arrays
$array = array_merge(array('tutor_id' => $tutor_id), array('tutor_id' => $tutor_id));

Your initial code
$array = [];
$array = ["tutor_id" => $tutor_id];
Now, if you want to add conditional merge, simply follow,
if($condition)
{
$array = array_merge($array, ["online" => $online]);
}
If $condition == true You final array will be,
$array = ['tutor_id' => $tutor_id, 'online' => $online];

You are almost there, just need to read a little bit more about associative arrays.
Solution:
$array = array();
$array["tutor_id"] = $tutor_id;
$array["online"] = $online;
$query_tutors = $this->db->get_where("tutor_info", $array);
This way your $array will have all indexes which you want.
You can do something like this:
$array = array();
if (!empty($tutor_id))
{
$array["tutor_id"] = $tutor_id;
}
if (!empty($online))
{
$array["online"] = $online;
}
$query_tutors = $this->db->get_where("tutor_info", $array);

Related

How to combine multidimensional array

How to combine multidimension array
<?php
$array[0] = [1=>[2=>[4=>[20=>""]]]];
$array[1] = [1=>[2=>[5=>[21=>""]]]];
$array[2] = [1=>[2=>[5=>[22=>""]]]];
$array[3] = [1=>[2=>[5=>[23=>""]]]];
$array[4] = [1=>[2=>[5=>[25=>""]]]];
$array[5] = [3=>[9=>[12=>[33=>""]]]];
$array[6] = [3=>[9=>[12=>[34=>""]]]];
$array[7] = [3=>[9=>[12=>[38=>""]]]];
?>
how to convert to be like:
$arrays = [1=>[2=>[4=>[20=>""],5=>[21=>"",22=>"",25=>""]]],[3=> [9 => [12 => [33 => "",38 => ""]]]]];
I am tried using array_merge :
$arrays = [];
foreach ($array as $val)
{
$arrays = array_merge($arrays,$val);
}
but the result always the first dimension make increment by that self
I already tried some func(like $arrays = $arrays+$val,array_push etc
) since 2 month ago I thought use array_merge is fine but the issue is make increment by that self so I am still not found the solution, I was also search on google and still no found about this.
Use one of the built-in array functions array_merge_recursive or array_replace_recursive. The code looks like:
$arrays = [];
foreach ($array as $val)
{
$arrays = array_replace_recursive($arrays,$val);
}
http://php.net/manual/en/function.array-merge-recursive.php

How to prevent duplicate keys from array_push

I have 2 2D arrays, how can i get the unique keys and only push those? For example:
$array = json_decode('[{"7654321":1368356071},{"1234567":1368356071}]',true);
$array2 = array(array(1234567 => time()), array(7654321 => time()), array(2345678 => time()));
//array_push($array, $array2[2]);
-- How can I dynamically get the unique key like $array2[2] in this example?
why not to use array_unique() function in php? http://php.net/manual/ru/function.array-unique.php
You mean, you would like to push into another array (let's say in $keys_unique) whatever key(s) that are present only in one of the first two arrays, but not present in both of them?
Try this:
$arrays_mixed = array( //your $array and $array2; you can put as many arrays as you want here
json_decode('[{"7654321":1368356071},{"1234567":1368356071}]',true)
,array(array(1234567 => time()), array(7654321 => time()), array(2345678 => time()))
);
//begin getting all keys
$arrays_keys = array(); //will hold all keys from arrays_mixed
$keys_unique = array(); //will hold all unique keys out of arrays_key
for($x=0;$x<count($arrays_mixed);$x++){
$arrays_keys[$x] = array(); //prepares a "keys holder"
$toflatten = $arrays_mixed[$x];
$c1 = 0;
do{
$arrmixed = array();
$arrclean = array();
foreach($toflatten as $a){
$arrmixed = $this->keys_finder($a,1);
$arrclean[$c1] = $this->keys_finder($a,2);
$c1++;
}
$toflatten = $arrmixed;
}while(is_array($toflatten));
for($c2=0;$c2<$c1;$c2++)
foreach($arrclean[$c2] as $ac)
array_push($arrays_keys[$x],$ac);
}//end geting all keys
//begin finding unique keys
foreach($arrays_keys as $ak)
foreach($ak as $add)
$keys_unique = $this->unique_inserter($arrays_keys,$keys_unique,$add);
//end finding unique keys
Here are the functions you need
function unique_inserter($arrays_keys,$keys_unique,$add){
$detector = 0; //detects how many arrays contain a value
foreach($arrays_keys as $ak)
if(in_array($add,$ak))
$detector++;
if($detector<2) //if value is found in one array only
array_push($keys_unique,$add);
return $keys_unique;
}
function keys_finder($array,$return){
$arrmixed = array();
$arrclean = array();
foreach($array as $key=>$a)
if(is_array($a))
foreach($a as $aa)
array_push($arrmixed,$aa);
else
array_push($arrclean,$key);
switch($return){
case 1:
return (count($arrmixed)==0)?'':$arrmixed;
break;
case 2:
return $arrclean;
break;
}
}
I have tested this code and it works on my side. Hope it helps.

How do I select last array per key in a multidimensional array

Given the following php array
$a = array(
array('a'=>'111','b'=>'two','c'=>'asdasd'),
array('a'=>'111','b'=>'one','c'=>'sdvsdfs'),
array('a'=>'111','b'=>'three','c'=>'vbndfgn'),
array('a'=>'222','b'=>'nine','c'=>'dfhfnd')
);
how can I return only the last array per array key 'a'?
Desired result:
$new = array(
array('a'=>'111','b'=>'three','c'=>'vbndfgn'),
array('a'=>'222','b'=>'nine','c'=>'dfhfnd')
);
If I were you, I'd try to store it in a better format that makes retrieving it a bit easier. However, if you are stuck with your format, then try:
$a = array(
array('a'=>'111','b'=>'two','c'=>'asdasd'),
array('a'=>'111','b'=>'one','c'=>'sdvsdfs'),
array('a'=>'111','b'=>'three','c'=>'vbndfgn'),
array('a'=>'222','b'=>'nine','c'=>'dfhfnd')
);
$tmp = array();
foreach ($a as $value) {
$tmp[$value['a']] = $value;
}
$new = array_values($tmp);
print_r($new);

PHP merge array(s) and delete double values

WP outputs an array:
$therapie = get_post_meta($post->ID, 'Therapieen', false);
print_r($therapie);
//the output of print_r
Array ( [0] => Massagetherapie )
Array ( [0] => Hot stone )
Array ( [0] => Massagetherapie )
How would I merge these arrays to one and delete all the exact double names?
Resulting in something like this:
theArray
(
[0] => Massagetherapie
[1] => Hot stone
)
[SOLVED] the problem was if you do this in a while loop it wont work here my solution, ty for all reply's and good code.: Its run the loop and pushes every outcome in a array.
<?php query_posts('post_type=therapeut');
$therapeAr = array(); ?>
<?php while (have_posts()) : the_post(); ?>
<?php $therapie = get_post_meta($post->ID, 'Therapieen', true);
if (strpos($therapie,',') !== false) { //check for , if so make array
$arr = explode(',', $therapie);
array_push($therapeAr, $arr);
} else {
array_push($therapeAr, $therapie);
} ?>
<?php endwhile; ?>
<?php
function array_values_recursive($ary) { //2 to 1 dim array
$lst = array();
foreach( array_keys($ary) as $k ) {
$v = $ary[$k];
if (is_scalar($v)) {
$lst[] = $v;
} elseif (is_array($v)) {
$lst = array_merge($lst,array_values_recursive($v));
}}
return $lst;
}
function trim_value(&$value) //trims whitespace begin&end array
{
$value = trim($value);
}
$therapeAr = array_values_recursive($therapeAr);
array_walk($therapeAr, 'trim_value');
$therapeAr = array_unique($therapeAr);
foreach($therapeAr as $thera) {
echo '<li><input type="checkbox" value="'.$thera.'">'.$thera.'</input></li>';
} ?>
The following should do the trick.
$flattened = array_unique(call_user_func_array('array_merge', $therapie));
or the more efficient alternative (thanks to erisco's comment):
$flattened = array_keys(array_flip(
call_user_func_array('array_merge', $therapie)
));
If $therapie's keys are strings you can drop array_unique.
Alternatively, if you want to avoid call_user_func_array, you can look into the various different ways of flattening a multi-dimensional array. Here are a few (one, two) good questions already on SO detailing several different methods on doing so.
I should also note that this will only work if $therapie is only ever a 2 dimensional array unless you don't want to flatten it completely. If $therapie is more than 2 dimensions and you want to flatten it into 1 dimension, take a look at the questions I linked above.
Relevant doc entries:
array_flip
array_keys
array_merge
array_unique
call_user_func_array
It sounds like the keys of the arrays you are generating are insignificant. If that's the case, you can do a simple merge then determine the unique ones with built in PHP functions:
$array = array_merge($array1, $array2, $array3);
$unique = array_unique($array);
edit: an example:
// Emulate the result of your get_post_meta() call.
$therapie = array(
array('Massagetherapie'),
array('Hot stone'),
array('Massagetherapie'),
);
$array = array();
foreach($therapie as $thera) {
$array = array_merge($array, $thera);
}
$unique = array_unique($array);
print_r($unique);
PHP's array_unique() will remove duplicate values from an array.
$tester = array();
foreach($therapie as $thera) {
array_push($tester, $thera);
}
$result = array_unique($tester);
print_r($result);

PHP - Automatically creating a multi-dimensional array

So here's the input:
$in['a--b--c--d'] = 'value';
And the desired output:
$out['a']['b']['c']['d'] = 'value';
Any ideas? I've tried the following code without any luck...
$in['a--b--c--d'] = 'value';
// $str = "a']['b']['c']['d";
$str = implode("']['", explode('--', key($in)));
${"out['$str']"} = 'value';
This seems like a prime candidate for recursion.
The basic approach goes something like:
create an array of keys
create an array for each key
when there are no more keys, return the value (instead of an array)
The recursion below does precisely this, during each call a new array is created, the first key in the list is assigned as the key for a new value. During the next step, if there are keys left, the procedure repeats, but when no keys are left, we simply return the value.
$keys = explode('--', key($in));
function arr_to_keys($keys, $val){
if(count($keys) == 0){
return $val;
}
return array($keys[0] => arr_to_keys(array_slice($keys,1), $val));
}
$out = arr_to_keys($keys, $in[key($in)]);
For your example the code above would evaluate as something equivalent to this (but will work for the general case of any number of -- separated items):
$out = array($keys[0] => array($keys[1] => array($keys[2] => array($keys[3] => 'value'))));
Or in more definitive terms it constructs the following:
$out = array('a' => array('b' => array('c' => array('d' => 'value'))));
Which allows you to access each sub-array through the indexes you wanted.
$temp = &$out = array();
$keys = explode('--', 'a--b--c--d');
foreach ($keys as $key) {
$temp[$key] = array();
$temp = &$temp[$key];
}
$temp = 'value';
echo $out['a']['b']['c']['d']; // this will print 'value'
In the code above I create an array for each key and use $temp to reference the last created array. When I run out of keys, I replace the last array with the actual value.
Note that $temp is a REFERENCE to the last created, most nested array.

Categories