What I want to do is:
$array_data = array( "a" => array(1, 2, 3), "b" => array( 1, 2, 3 ) );
$table_converted = CONVERT_TO_MYSQL_TABLE( $array_data );
while ($row = mysql_fetch_assoc( $table_converted )) {
echo $row['a'] . " union " . $row['b'];
}
Loop through the array, and construct an array with the same keys but in different order:
$array_data = array( "a" => array(1, 2, 3), "b" => array( 1, 2, 3 ) );
$results = array();
foreach ($array_data as $name => $values)
{
foreach ($values as $i => $value)
{
$results[$i][$name] = $value;
}
}
print_r($results);
Related
I have a an array looking like this:
$array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);
I would like to sum values foreach "unique" key when only the first character is considered. The result should then be:
$newarray = array("a" => 3, "b" => 5);
I have tried using a foreach() loop within another foreach() loop like this:
foreach ($xml->children() as $output) {
foreach ($array as $key => $value) {
if (substr($key,0,1) == $output->KEY) {
$sum += $value; echo $sum;
}
}
}
It didn't work as the results apparently added the prior calculations.
Simple solution:
$final_array=[];
foreach($array as $key=>$value){
$final_array[$key[0]] = (isset($final_array[$key[0]])) ? $final_array[$key[0]]+$value : $value;
}
print_r($final_array);
Output:- https://3v4l.org/tZ4Ei
You can try this one. It will take first letter from your key and make sum of all values with that first letter keys.
<?php
$sum = [];
foreach ($array as $key => $value) {
$letter = substr($key,0,1);
if (!isset($sum[$letter])){$sum[$letter] = 0;}
$sum[$letter] += $value;
}
var_dump($sum);
A simple isset should do it:
$array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);
$result = array();
foreach ($array as $oldkey => $val) {
$newkey = substr($oldkey, 0, 1);
if (isset($result[$newkey]) === false)
$result[$newkey] = $val;
else
$result[$newkey] += $val;
}
var_dump($result);
Try this way
$array = array('a1' => 0, 'a2' => 2, 'a3' => 3, 'b1' => 2, 'b2' => 3);
$result = array();
foreach($array as $key => $value){
if(isset($result[$key[0]])){
$result[$key[0]] = $result[$key[0]]+$value;
} else {
$result[$key[0]] = $value;
}
}
print_r($result);
Quick and Easy, you can have any number of numbers in the array after the characters.
<?php
$array = ["a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3];
$newArray = [];
foreach ($array as $key => $value) {
$key = preg_replace("/[0-9]*$/", "", $key);
$newArray[$key] = (isset($newArray[$key])) ? $newArray[$key] + $value : $value;
}
print_r($newArray);
I want to compare keys from one array against values from another array, and when a match is made to store the value from the first array (whose key matched the value in the second one).
With my code, it always echoes out 4. How can I modify it so that it echoes out 1 2 3 4?
The code:
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
while ($el = current($second)) {
$d .= ','.key($second);
next($second);
}
$d = ltrim($d, ',');
$d = explode(',', $d);
foreach ($first as $the_tax) {
foreach ($d as $key => $v) {
if (in_array($v, $first)) {
$t = $second[$v];
}
}
echo $t.'<br>';
}
To be honsest, if you wouldn't explain your goal, I wouldn't even understand what you're trying to do by your code. Try like this:
<?php
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
$intersect = array_intersect($first, array_keys($second));
foreach($intersect as $key)
echo $second[$key];
?>
You should move/add add an echo statement into the block where you assign the value of $t, maybe this way:
foreach ($first as $the_tax) {
foreach ($d as $key => $v) {
if (in_array($v, $first)) {
$t = $second[$v];
echo $t.' ';
}
}
echo '<br>';
}
you can flip the keys in second array, and then take the intersection of the 2. something along these lines
<?php
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
$flipped = array_flip($second);
print implode(' ',array_keys(array_intersect($flipped, $first)));
?>
I trying to get the minimum values from the any column contains "xx" in the column name.
Below is my code:
<?php
$array = array(
array(
'id' => 1,
'10xx' => 14,
'11xx' => 32,
'12xx' => 4
),
array(
'id' => 2,
'10xx' => 13,
'11xx' => 36,
'12xx' => 41
)
);
foreach($array as $item)
{
$lowestKey = '';
foreach($item as $key => $value)
{
if(strpos($key, 'xx') === 0)
{
if($lowestKey == '')
{
$lowestKey = $key;
}
else
{
if($value < $item[$lowestKey])
{
$lowestKey = $key;
}
}
}
}
echo 'lowest for id ' . $item['id'] . ': ' . $item[$lowestKey] . "\n";
}
?>
You have a function already for it:
http://php.net/manual/en/function.min.php
echo min(2, 3, 1, 6, 7); // 1
echo min(array(2, 4, 5)); // 2
echo min(0, 'hello'); // 0
echo min('hello', 0); // hello
echo min('hello', -1); // -1
Combine it with array_values if this fits better your needs.
function _getNumber($array) {
return $array['id'];
}
$numbers = array_map('_getNumber', $array);
OR
$numbers = array_map(function($array) {
return $array['id'];
}, $array);
echo $min = min($numbers);
echo $max = max($numbers);
function find_lowest($array){
$new_array = array();
foreach($array as $key => $val ){
if(is_array($val)){
$new_array[$key] = find_lowest($val);
}else{
$new_array[$key] = $val ;
}
}
return min($new_array);
}
$array = array( array( 'id' => 1,
'10xx' => 14,
'11xx' => 32,
'12xx' => 4
),
array(
'id' => 2,
'10xx' => 13,
'11xx' => 36,
'12xx' => 41
)
);
echo find_lowest($array);
Instead of looping again inside just use the min() function.
$lowest_keys = array();
foreach($array as $item)
{
unset( $item[ 'id' ] );
$lowest_keys[] = min( $item );
}
Iterate each row/subarray with a foreach() loop or array_walk().
Extract and display the id (first element) value with array_shift().
Call min() on the remaining values in the respective subarray to determine the lowest value.
No conditional expressions. No unnecessary variables. Clean, concise, and effective.
Code: (Demo)
$array = [
['id' => 1, '10xx' => 14, '11xx' => 32, '12xx' => 4],
['id' => 2, '10xx' => 13, '11xx' => 36, '12xx' => 41]
];
array_walk($array, function($row) {
echo array_shift($row) , " : " , min($row) , "\n";
});
Output:
1 : 4
2 : 13
$array = array(
array(
'id' => 14,
'10xx' => 14,
'11xx' => 32,
'12xx' => 4
),
array(
'id' => 2,
'10xx' => 13,
'11xx' => 36,
'12xx' => 41
)
);
$lowestKey = '';
foreach($array as $arra){
foreach ($arra as $key=>$value){
if ($key == 'id'){
if(($value < $lowestKey )||( $lowestKey== '')){
$lowestKey = $value;
}
}
}
}
echo $lowestKey;
I have a simple associative array.
<?php
$assocArray = array('a' => 1, 'b' => 2, 'c' => 3);
?>
Using only while loop, how can I print it in this result?
$a = 1
$b = 2
$c = 3
This is my current solution but I think that this is not the efficient/best way to do it?
<?php
$assocArray = array('a' => 1, 'b' => 2, 'c' => 3);
$keys = array_keys($assocArray);
rsort($keys);
while (!empty($keys)) {
$key = array_pop($keys);
echo $key . ' = ' . $assocArray[$key] . '<br />';
};
?>
Thanks.
try this syntax and this is best efficient way to do your job...........
while (list($key, $value) = each($array_expression)) {
statement
}
<?php
$data = array('a' => 1, 'b' => 2, 'c' => 3);
print_r($data);
while (list($key, $value) = each($data)) {
echo '$'.$key .'='.$value;
}
?>
For reference please check this link.........
Small Example link here...
The best and easiest way to loop through an array is using foreach
foreach ($assocArray as $key => $value)
echo $key . ' = ' . $value . '<br />';
Try this;
$assocarray = array('a' => 1, 'b' => 2, 'c' => 3);
$keys = array_keys($assocarray);
rsort($keys);
while (!empty($keys)) {
$key = array_pop($keys);
echo $key . ' = ' . $assocarray[$key] . '<br />';
};
I have a simple solution for this, it will get the job done..
$x = array(0=>10,1=>11,2=>"sadsd");
end($x);
$ekey = key($x);
reset($x );
while(true){
echo "<br/>".key($x)." = ".$x[key($x)];
if($ekey == key($x) )break;
next($x);
}
Try code below:
$assocArray = array('a' => 1, 'b' => 2, 'c' => 3);
$obj = new ArrayObject($assocArray);
foreach ( $obj as $key => $value ) {
echo '$' . $key .'='. $value . "<br/>";
}
I'm trying to merge these 2 arrays
$arr1 = array('a' => "1", 'b' => "2", 'c' => "3");
$arr2 = array('a' => "9", 'b' => "8", 'd' => "7");
into an array that looks like this
$arr1 = array(
'a' => array("1", "9"),
'b' => array("2", "8"),
'c' => array("3", ""),
'd' => array("", "7")
);
The tricky part is the blanks. I need to preserve them in place.
Thanks
function merge()
{
$array_of_arrays = func_get_args();
//get all the unique keys
$final_array_keys = array_keys( call_user_func_array( "array_merge", $array_of_arrays ) );
//make final array
$final_array = array();
foreach( $final_array_keys as $key ) {
foreach( $array_of_arrays as $current_array ) {
$final_array[$key][] = array_key_exists( $key, $current_array ) ? $current_array[$key] : "";
}
}
return $final_array;
}
Try this:
$arr1 = array('a' => "1", 'b' => "2", 'c' => "3");
$arr2 = array('a' => "9", 'b' => "8", 'd' => "7");
$keys = array();
$merged = array()
for($arr1 as $key=>$val)
{
array_push($keys,$key);
}
for($arr2 as $key=>$val)
{
array_push($keys,$key);
}
for($key in keys)
{
$merged[$key] = array("","");
if(isset($arr1[$key])) $merged[$key][0] = $arr1[$key];
if(isset($arr2[$key])) $merged[$key][1] = $arr2[$key];
}
foreach (array_merge($arr1, $arr2) as $key => $val)
{
$result[$key] = array("{$arr1[$key]}", "{$arr2[$key]}");
}
var_dump($result);
here's my suggestion. It'll combine an arbitrary number of arrays according to what you described.
error_reporting(E_ALL | E_STRICT);
header('Content-Type: text/plain');
$arr1 = array('a' => "1", 'b' => "2", 'c' => "3");
$arr2 = array('a' => "9", 'b' => "8", 'd' => "7");
$arr = combine($arr1, $arr2);
print_r($arr);
function combine() {
$keys = array();
foreach (func_get_args() as $arr) {
if (is_array($arr)) {
$keys += $arr;
}
}
$keys = array_keys($keys);
$values = array_pad(array(), count($keys), array());
$ret = array_combine($keys, $values);
foreach (func_get_args() as $arr) {
foreach ($keys as $k) {
$v = array_key_exists($k, $arr) ? $arr[$k] : '';
array_push($ret[$k], $v);
}
}
return $ret;
}
Output:
Array
(
[a] => Array
(
[0] => 1
[1] => 9
)
[b] => Array
(
[0] => 2
[1] => 8
)
[c] => Array
(
[0] => 3
[1] =>
)
[d] => Array
(
[0] =>
[1] => 7
)
)
I like cletus's approach, so I've just made sure it works :)
function combine() {
$keys = array();
foreach (func_get_args() as $arr) {
if (is_array($arr)) {
$keys = array_merge($keys, array_keys($arr));
}
}
$keys = array_unique($keys);
$values = array_pad(array(), count($keys), array());
$ret = array_combine($keys, $values);
foreach (func_get_args() as $arr) {
foreach ($keys as $k) {
$v = '';
if (array_key_exists($k, $arr)){
$v = $arr[$k];
}
array_push($ret[$k], $v);
}
}
return $ret;
}