I have defined two arrays as
$array1 = (8,10);
Array2 was array of stdobjects which was later converted into below using json decode, encode. Php echo output of the same is below:
$array2 = Array
(
[0] => Array
(
[id] => 6
)
[1] => Array
(
[id] => 8
)
[2] => Array
(
[id] => 10
)
)
Later I created one array
foreach( $array2 as $value )
{
$valuesArray[] = array('',$value['id'],Input::get('date'),'0');
}
What I am trying to do is compare array1 with valuesarray. If $value['id'] i.e. second element matches with any of the element in array1, I will save 4th element of $nnn as 1. If it doesnt match with any of the element, I will save it as 0.
My code below:
foreach ($valuesArray as $value2)
{
foreach ($array1 as $value1)
{
if ($value2[1] == $value1)
{$x = 1;}
else
{$x = 0;}
}
$nnn[] = "('','".$value2[1]."','".Input::get('date')."','".$x."')";
}
echo '<pre>',print_r($nnn,1),'</pre>';
The output that I am getting is:
Array
(
[0] => ('','6','2016-04-25','0')
[1] => ('','8','2016-04-25','0')
[2] => ('','10','2016-04-25','1')
)
Correct output should be:
Array
(
[0] => ('','6','2016-04-25','1')
[1] => ('','8','2016-04-25','1')
[2] => ('','10','2016-04-25','0')
)
try this:
$nnn = array();
foreach ($valuesArray as $value) {
$x = (in_array($value[1], $array1))?1:0;
$nnn[] = "('','".$value[1]."','".Input::get('date')."','{$x}')";
}
Related
I have total 3 array
First array contains list of titles
Second array contains list of description
third array contains images
I have already combine 1st and 2nd array as a key of first array and value of second array and I also combine 1st and 3rd array as key of 1st and value of 3rd.
Following is my arrays
1 )
Array
(
[First] => FFFFFFFFFFFFFFFF
[Second] => ssss
[0] => Array
(
[First] => eae2d7b3f20250def1892bae1abaf07f.png
[Second] => ea7ca514d1ef580f85fb42c7cb425462.png
)
)
I want output like
Array
(
[First] => FFFFFFFFFFFFFFFF
[Second] => ssss
[First] => eae2d7b3f20250def1892bae1abaf07f.png
[Second] => ea7ca514d1ef580f85fb42c7cb425462.png
)
Code
foreach ($images as $key => $value) {
$values['image']= $value;
}
$data = array_combine($_POST['title'], $images);
$mainArray = array_combine($_POST['title'], $_POST['Description']);
array_push($mainArray,$data);
echo '<pre>';
print_r($mainArray);
How can I do this?
The code below should produce the format the array as required above, although it is not the most elegant way to flatten an array. It may be worthwhile looking at previous questions like How to Flatten a Multidimensional Array?
$newArr = array();
foreach ( $mainArray as $key => $val ) {
if ( is_array( $val ) ) {
foreach ( $val as $key2 => $val2 ) {
$newArr[$key2] = $val2;
}
} else {
$newArr[$key] = $val;
}
}
I have a simple Two array
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
When I print this arrays it should be like following:
Array
(
[0] => Array
(
[Peter] => 22
[Clark] => 32
[John] => 28
)
)
Array
(
[0] => Array
(
[demo] => 22
)
)
But I want to create third array which will be show demo kye value into first array like following:
Array
(
[0] => Array
(
[Peter] => 22
[Clark] => 32
[John] => 28
[demo] => 22
)
)
Can we do two array into single array in PHP like Above
Not sure what are you trying to achieve here...little more context would be helpful. But this is how you can do this,
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
$result[] = array_merge($ages[0],$ages1[0]);
This would do the job.
<?php
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
$output = prepend_array($ages,$ages1);
print_r($output);
// Function to prepend arrays
function prepend_array()
{
$num_args = count(func_get_args());
$new_array = array();
foreach (func_get_args() as $params){
foreach($params as $out_key => $param)
{
foreach($param as $key => $value)
$new_array[$out_key][$key] = $value;
}
}
return $new_array;
}
I am struggling with an array that I need to convert into a new array based on the unique array keys. My current result looks like below. Each array represent just a part of the desired result (pivot) where I need a [menu_name], [menu_url] and [menu_target] as result and when the next array begins with the same keys, etc. So the way I see it to achieve this is to construct a new array, each time an array_key_exist in the array. But i am unable to achieve this.
Array
(
Array
(
[menu_name] => Contact
)
Array
(
[menu_url] => /contact
)
Array
(
[menu_target] => _blank
)
Array
(
[menu_name] => Home
)
Array
(
[menu_url] => /home
)
Array
(
[menu_target] => _self
)
)
The desired array I want to create looks like this:
Array
(
[0] => Array
(
[menu_name] => Contact,
[menu_url] => /contact,
[menu_target] => _blank
)
[1] => Array
(
[menu_name] => Home,
[menu_url] => /home,
[menu_target] => _blank
)
)
Here is my code so far (incomplete):
$result = array();
foreach($array as $option => $value)
{
$result[$value->option_key] = $value->option_value;
$new_array = array();
if(array_key_exist($value->option_key, $new_array))
{
// here is where I get stuckā¦.
print_r($new_array);
}
}
I hope some one can get me in the right direction to further complete the code with the desired result.
You can use a var you increment each time key already exists :
$result = array();
$i = 0;
foreach($array as $option => $value)
{
if ( array_key_exists($value->option_key, $result[$i]) ) $i++;
$result[$i][$value->option_key] = $value->option_value;
}
Another way, is if the current batch of keys are complete, go to the next one and fill up the next one. Example:
$values = array(array('menu_name' => 'Contact'),array('menu_url' => '/contact'),array('menu_target' => '_blank'),array('menu_name' => 'Home'),array('menu_url' => '/home'),array('menu_target' => '_self'),);
$new_values = array();
$x = 0;
$columns = array_unique(array_map(function($var){
return key($var);
}, $values));
foreach($values as $value) {
$current_key = key($value);
$new_values[$x][$current_key] = reset($value);
if(array_keys($new_values[$x]) == $columns) $x++;
}
echo '<pre>';
print_r($new_values);
Sample Demo
Provided your answer is always grouped by threes, as posted in your example.
This is an alternative method to djidi's answer incase you wanted to see it done with silly loops.
$new = array_chunk($a, 3);
$d = array();
foreach($new as $i => $group) {
foreach($group as $index => $item) {
foreach($item as $name=>$val) {
$d[$i][$name] = $val;
}
}
}
Which returns:
Array
(
[0] => Array
(
[menu_name] => Contact
[menu_url] => /contact
[menu_target] => _blank
)
[1] => Array
(
[menu_name] => Home
[menu_url] => /home
[menu_target] => _self
)
)
Example Demo
I have following array,
Array
(
[Char100_1] => Array
(
[0] => Array
(
[Char100_1] => Mr S Kumar
)
[1] => Array
(
[Char100_1] => Mr S Kumar2
)
)
[Char100_13] => Array
(
[0] => Array
(
[Char100_13] => 159.9
)
[1] => Array
(
[Char100_13] => 119.9
)
)
[Char100_14] => Array
(
[0] => Array
(
[Char100_14] => 191.88
)
[1] => Array
(
[Char100_14] => 143.88
)
)
)
which is created dynamically from a database query result and some loops.
Now I wanted to convert this array into something like below,
Array
(
[0] => Array
(
[Char100_1] => Mr S Kumar
[Char100_13] => 159.9
[Char100_14] => 191.88
)
[1] => Array
(
[Char100_1] => Mr S Kumar2
[Char100_13] => 119.9
[Char100_14] => 143.88
)
)
I have tried looping through them but its not working.
<?php
/* database process to create array */
$contentArray = array();
foreach($newData['DataField'] as $ndata) :
$responsedata = getAppContent($appid, $ndata);
while($haveresult = mysql_fetch_assoc($responsedata))
{
$contentArray[$ndata][] = $haveresult;
}
endforeach;
/* for getting resulting array start */
$newdataArray = array();
foreach($contentArray as $field => $value):
$newdataArray[$field] = array();
foreach( $value as $val ) :
$newdataArray[$field] = $val;
endforeach;
endforeach;
?>
If you can't change the query (as suggested in the comments), then the following should work:
$output = array();
foreach ($array as $a) {
foreach ($a as $k => $b) {
if (empty($output[$k])) {
$output[$k] = array();
}
$output[$k] += $b;
}
}
I observe that you are transposing the arrays. i.e all the zero subscript values together and all the one subscript values together.
Therefore your outer subscript should be the '0' and '1'. These are available in the inner loop. So, the inner loop index becomes the outer array index. And the inner loop value, which is an array, you need to take the 'current' value of.
/* for getting resulting array start (PHP 5.3.18) */
$newdataArray = array();
foreach($contentArray as $field => $value):
foreach( $value as $idx => $val ): // $idx takes value 0 or 1. $val is an array
$newdataArray[$idx][$field] = current($val);
endforeach;
endforeach;
print_r($newdataArray);
As long as all of your arrays have the same amount of values containing them a for loop will do:
$NewDataArray = array();
for ($a = 0; $a < $Numberofvaluesineacharray; $a++){
$NewDataArray[$a] = $NewDataArray[$array1[$a], $array2[$a],.....arrayn[$a];
}
I have an 2d array which returns me this values:
Array (
[0] => Array (
[0] => wallet,pen
[1] => perfume,pen
)
[1] => Array (
[0] => perfume, charger
[1] => pen,book
).
Out of this i would like to know if it is possible to create a function which would combine the array going this way,and create a new one :
if for example [0] => Array ( [0] => wallet,pen [1] => perfume,pen ) then should be equal to
[0] => Array ( [0] => wallet,pen, perfume ) because there is a common word else do nothing.
And also after that retrieve each words as strings for further operations.
How can i make the values of such an array unique. Array ( [0] => Array ( [0] => wallet [1] => pen [2] => perfume [3] => pen) ) as there is pen twice i would like it to be deleted in this way ( [0] => Array ( [0] => wallet [1] => pen [2] => perfume) )
It's just a matter of mapping the array and combining the inner arrays:
$x = [['wallet,pen', 'perfume,pen'], ['perfume,charger', 'pen,book']];
$r = array_map(function($item) {
return array_unique(call_user_func_array('array_merge', array_map(function($subitem) {
return explode(',', $subitem);
}, $item)));
}, $x);
Demo
This first splits all the strings based on comma. They are then merged together with array_merge() and the duplicates are removed using array_unique().
See also: call_user_func_array(), array_map()
Try this :
$array = Array (Array ( "wallet,pen", "perfume,pen" ), Array ( "perfume, charger", "pen,book" ));
$res = array();
foreach($array as $key=>$val){
$temp = array();
foreach($val as $k=>$v){
foreach(explode(",",$v) as $vl){
$temp[] = $vl;
}
}
if(count(array_unique($temp)) < count($temp)){
$res[$key] = implode(",",array_unique($temp));
}
else{
$res[$key] = $val;
}
}
echo "<pre>";
print_r($res);
output :
Array
(
[0] => wallet,pen,perfume
[1] => Array
(
[0] => perfume, charger
[1] => pen,book
)
)
You can eliminate duplicate values while pushing them into your result array by assigning the tag as the key to the element -- PHP will not allow duplicate keys on the same level of an array, so any re-encountered tags will simply be overwritten.
You can use recursion or statically written loops for this task.
Code: (Demo)
$result = [];
foreach ($array as $row) {
foreach ($row as $tags) {
foreach (explode(',', $tags) as $tag) {
$result[$tag] = $tag;
}
}
}
var_export(array_values($result));
Code: (Demo)
$result = [];
array_walk_recursive(
$array,
function($v) use(&$result) {
foreach (explode(',', $v) as $tag) {
$result[$tag] = $tag;
}
}
);
var_export(array_values($result));