I have a lot of array based explode a string like this :
$size = explode(",", $row->SIZE);
$coil_no = explode(",", $row->COIL_NO);
$net = explode(",", $row->NET);
$gross = explode(",", $row->GROSS);
$contract_no = explode(",", $row->CONTRACT_NO);
$location = explode(",", $row->LOCATION);
How can I unite those array into one multidimensional array ?
I have try like this :
foreach ($size as $value) {
foreach ($coil_no as $coil) {
$detail[] = array(
"coil_no" => $coil,
"size" => $value
);
}
}
you know the result the looping is loop weird,
I need more elegant array, like
foreach ($unite_array as $row) :
echo "<tr> $row->size </tr>" ;
endforeach;
What the best way to unite those array ?
You can write your own function which does the grouping on keys as required, see example below:
function array_group(){
if(func_num_args() > 0) {
$params = func_get_args();
$result = array();
foreach($params as $key => $param) {
foreach($param['values'] as $k => $value) {
$result[$k][$param['alias']] = $value;
}
}
return $result;
}
return false;
}
$rows = array_group(
array('alias' => 'size', 'values' => array(1,2,3,4,5)),
array('alias' => 'coil_no', 'values' => array(6,7,8,9,10)),
array('alias' => 'net', 'values' => array(11,12,13,14,15)),
array('alias' => 'gross', 'values' => array(16,17,18,19,20)),
array('alias' => 'contract_no', 'values' => array(21,22,23,24,25)),
array('alias' => 'location', 'values' => array(26,27,28,29,30))
);
print_r($rows);
And you can access it like:
foreach ($rows as $row) :
echo "<tr> {$row['size']} </tr>" ;
endforeach;
Related
I have this multidimensional array:
$value = [
'name' => ['silverado', 'civic'],
'type' => ['truck', 'car'],
];
I want to basically sort both of these child arrays by the values of name, ascending.
I have this code, which works:
$value = [
'name' => ['silverado', 'civic'],
'type' => ['truck', 'car'],
];
$name_type = [];
$columns = [];
foreach ($value['name'] as $k => $v) {
$name_type[$v] = $value['type'][$k];
}
ksort($name_type);
foreach ($name_type as $name => $type) {
$columns['name'][] = $name;
$columns['type'][] = $type;
}
$value = $columns;
I'm just curious if there is a better way of coding this rather than using 2 foreach loops.
You can use array_multisort, check Demo
array_multisort($value["name"],$value["type"]);
first array like this
$zones_array1 = array();
$zones_array1[] = array('id' => 'Alabama', 'text' => 'Alabama');
$zones_array1[] = array('id' => 'Alaska', 'text' => 'Alaska');
$zones_array1[] = array('id' => 'Arizona', 'text' => 'Arizona');
$zones_array1[] = array('id' => 'Arkansas', 'text' => 'Arkansas');
second array like this
$zones_array2 = array();
$zones_array2[] = array('id' => 'Alaska', 'text' => 'Alaska');
$zones_array2[] = array('id' => 'Arizona', 'text' => 'Arizona');
i want filter these two array and i want final result as array like this
first array like this
$zones_array3 = array();
$zones_array3[] = array('id' => 'Alabama', 'text' => 'Alabama');
$zones_array3[] = array('id' => 'Arkansas', 'text' => 'Arkansas');
please help me
You can use php 'in_array' to check weather an element exists inside other array or not. In you case the array is multidimensional so stored all the id's inside a newly created array and then compared the given array with that.
$check_array = array();
foreach ($zones_array1 as $arr1){
$check_array[] = $arr1['id'];
}
$zones_array3 = array();
foreach ($zones_array2 as $arr2){
if (!in_array($arr2['id'], $check_array))
{
$zones_array3[] = $arr2;
}
}
echo '<pre>';
print_r($zones_array3);
Simply try:
function udiffCompare($a, $b)
{
return $a['id'] == $b['id'] ? 0 : -1;
}
$arrdiff = array_udiff($zones_array1, $zones_array2, 'udiffCompare');
echo '<pre>';
print_r($arrdiff);
array_udiff() compares each element of the first array-argument against all the elements of the second array-argument using the provided callback function. If the callback returns zero for any of the comparisons then the element of the array in the first argument will not be present in the returned array of the function.
You will try it :
function unique_multidim_array($array, $key){
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val){
if(!in_array($val[$key],$key_array)){
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
$zones_array1 = array_merge($zones_array2, $zones_array3);
$zones_array1 = unique_multidim_array($zones_array1, 'id');
print_r($zones_array1);
Please try this
array_push($zones_array1,$zones_array2);
print_r(array_unique($zones_array1));
I am not sure.
I was wondering when working with multimedional arrays, if a certain key is the same, is there a way to combine the contents of other keys into its own array if a certain key is the same?
Something like this:
// name is the same in both arrays
array(
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '1234567'
),
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '5556734'
)
)
into something like this
array(
array(
'name' => 'Pepsi',
'store' => array('Over here', 'Over here'),
'number' => array('1234567', '5556734')
)
)
The defining key is checking if the name element is the same for the other arrays.
You can try a function like this.
function mergeByKey($array,$key){
$tmp_array = array();
foreach ( $array as $k => $row ) {
$merged = false;
foreach ($tmp_array as $k2 => $tmp_row){
if ($row[$key] == $tmp_row[$key]){
foreach ( $row as $k3 => $value ) {
if ($k3 == $key) continue;
$tmp_array[$k2][$k3][] = $value;
$merged = true;
}
}
if ($merged) break;
}
if (!$merged) {
$new_row = array();
foreach ( $row as $k4 => $value ) {
if ($k4 == $key) $new_row[$k4] = $value;
else $new_row[$k4] = array($value);
}
$tmp_array[] = $new_row;
}
}
foreach ( $tmp_array as $t => $row ) {
foreach ( $row as $t2 => $value ) {
if ( count($value) == 1 && $t2 != $key ) $tmp_array[$t][$t2] = $value[0];
}
}
return $tmp_array;
}
passing the array as first parameter and the key as second one.
I'm referencing to your array structure
edited: missed a piece
edited2: if resultin array contains elements with one string, it returns a string and not a array with one element
demo
This function uses a given field name as the grouping identifier and turns all other fields into arrays.
Note that single occurrences of your field name will yield arrays with a single element for the other fields. I wasn't sure whether that's a desirable trait, but just making sure you know ;-)
$arr = array(
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '1234567'
),
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '5556734'
)
);
function mergeArray($array, $column)
{
$res = array();
foreach ($array as $item) {
foreach ($item as $key => $value) {
if ($key === $column) {
$res[$column][$key] = $value;
} else {
$res[$column][$key][] = $value;
}
}
}
return array_values($res);
}
print_r(mergeArray($arr, 'name'));
Demo
Thanks to Gianni Lovece for her answer but I was able to develop a much simpler solution based on this problem. Just plug in the $result_arr to browse through and the $key you want to use as basis and it immediately outputs a multidimensional array with non-repeating values for repeating elements (see example below).
function multiarray_merge($result_arr, $key){
foreach($result_arr as $val){
$item = $val[$key];
foreach($val as $k=>$v){
$arr[$item][$k][] = $v;
}
}
// Combine unique entries into a single array
// and non-unique entries into a single element
foreach($arr as $key=>$val){
foreach($val as $k=>$v){
$field = array_unique($v);
if(count($field) == 1){
$field = array_values($field);
$field = $field[0];
$arr[$key][$k] = $field;
} else {
$arr[$key][$k] = $field;
}
}
}
return $arr;
}
For example, in the sample array for this question, running multiarray_merge($mysample, 'name') returns
array(
'Pepsi' => array(
'name' => 'Pepsi',
'store' => 'Over here', // String: Not an array since values are not unique
'number' => array('1234567', '5556734') // Array: Saved as array since values are unique
)
);
Any help is appreciated.
I have an array that is forfetch like this. The reason is to brake down a product in individual arrays. However I can not figure out what statement to put in the while loop so i can loop through each array in $row. initially the statement should be
while ($row = mysql_fetch_assoc($result))
however this was already done to be able to sort the array.
$sorted = array_orderby($newarray, 'volume', SORT_DESC, 'edition', SORT_ASC);
foreach($sorted as $row)
{
while( ??????? )
{
$row = build_items($row);
$template->assign_block_vars('featured_items', array(
'ID' => $row['id'],
'IMAGE' => $row['pict_url'],
'TITLE' => $row['title'],
'SUBTITLE' => $row['subtitle'],
'BUY_NOW' => ($difference < 0) ? '' : $row['buy_now'],
'B_BOLD' => ($row['bold'] == 'y')
));
$k++;
$feat_items = true;
}
}
Just found the answer. Sorry guys im new at PHP.
foreach($sorted AS $row) {
$row = build_items($row);
// time left till the end of this auction
$s_difference = time() - $row['starts'];
$difference = $row['ends'] - time();
$bgcolour = ($k % 2) ? 'bgcolor="#FFFEEE"' : '';
$template->assign_block_vars('featured_items', array(
'ID' => $row['id'],
'IMAGE' => $row['pict_url'],
'TITLE' => $row['title'],
'SUBTITLE' => $row['subtitle'],
'BUY_NOW' => ($difference < 0) ? '' : $row['buy_now'],
'BID' => $row['current_bid'],
'BIDFORM' => $system->print_money($row['current_bid']),
'TIMELEFT' => FormatTimeLeft($difference),
'NUMBIDS' => $row['num_bids'],
'B_BOLD' => ($row['bold'] == 'y')
));
$k++;
$feat_items = true;
}
foreach($sorted AS $rows) {
foreach($rows AS $row) {
...
}
}
or with keys/indices
foreach($sorted AS $key => $rows) {
foreach($rows AS $index => $row) {
Yes.., we can use foreach to print all the values in an array.
Example: I have an array called "data" (SQLITE dynamic data). I want to print all the values which are there on "data" array.
By using following sample code we can print the values in a table format.
foreach ($data as $item) {
$date = $item['date'];
$url = $item['url'];
$name = $item['name'];
echo"
<tr>
<td>$date</td>
<td>$name</td>
<td>$url</td>
</tr>
";
}
Please let me know if i did any mistakes here, sorry for my bad English.
In an array such as the one below, how could I rename "fee_id" to "id"?
Array
(
[0] => Array
(
[fee_id] => 15
[fee_amount] => 308.5
[year] => 2009
)
[1] => Array
(
[fee_id] => 14
[fee_amount] => 308.5
[year] => 2009
)
)
foreach ( $array as $k=>$v )
{
$array[$k] ['id'] = $array[$k] ['fee_id'];
unset($array[$k]['fee_id']);
}
This should work
You could use array_map() to do it.
$myarray = array_map(function($tag) {
return array(
'id' => $tag['fee_id'],
'fee_amount' => $tag['fee_amount'],
'year' => $tag['year']
); }, $myarray);
$arrayNum = count($theArray);
for( $i = 0 ; $i < $arrayNum ; $i++ )
{
$fee_id_value = $theArray[$i]['fee_id'];
unset($theArray[$i]['fee_id']);
$theArray[$i]['id'] = $fee_id_value;
}
This should work.
Copy the current 'fee_id' value to a new key named 'id' and unset the previous key?
foreach ($array as $arr)
{
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
There is no function builtin doing such thin afaik.
This is the working solution, i tested it.
foreach ($myArray as &$arr) {
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
The snippet below will rename an associative array key while preserving order (sometimes... we must). You can substitute the new key's $value if you need to wholly replace an item.
$old_key = "key_to_replace";
$new_key = "my_new_key";
$intermediate_array = array();
while (list($key, $value) = each($original_array)) {
if ($key == $old_key) {
$intermediate_array[$new_key] = $value;
}
else {
$intermediate_array[$key] = $value;
}
}
$original_array = $intermediate_array;
Converted 0->feild0, 1->field1,2->field2....
This is just one example in which i get comma separated value in string and convert it into multidimensional array and then using foreach loop i changed key value of array
<?php
$str = "abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu;
echo '<pre>';
$arr1 = explode("\n", $str); // this will create multidimensional array from upper string
//print_r($arr1);
foreach ($arr1 as $key => $value) {
$arr2[] = explode(",", $value);
foreach ($arr2 as $key1 => $value1) {
$i =0;
foreach ($value1 as $key2 => $value2) {
$key3 = 'field'.$i;
$i++;
$value1[$key3] = $value2;
unset($value1[$key2]);
}
}
$arr3[] = $value1;
}
print_r($arr3);
?>
I wrote a function to do it using objects or arrays (single or multidimensional) see at https://github.com/joaorito/php_RenameKeys.
Bellow is a simple example, you can use a json feature combine with replace to do it.
// Your original array (single or multi)
$original = array(
'DataHora' => date('YmdHis'),
'Produto' => 'Produto 1',
'Preco' => 10.00,
'Quant' => 2);
// Your map of key to change
$map = array(
'DataHora' => 'Date',
'Produto' => 'Product',
'Preco' => 'Price',
'Quant' => 'Amount');
$temp_array = json_encode($original);
foreach ($map AS $k=>$v) {
$temp_array = str_ireplace('"'.$k.'":','"'.$v.'":', $temp);
}
$new_array = json_decode($temp, $array);
Multidimentional array key can be changed dynamically by following function:
function change_key(array $arr, $keySetOrCallBack = [])
{
$newArr = [];
foreach ($arr as $k => $v) {
if (is_callable($keySetOrCallBack)) {
$key = call_user_func_array($keySetOrCallBack, [$k, $v]);
} else {
$key = $keySetOrCallBack[$k] ?? $k;
}
$newArr[$key] = is_array($v) ? array_change_key($v, $keySetOrCallBack) : $v;
}
return $newArr;
}
Sample Example:
$sampleArray = [
'hello' => 'world',
'nested' => ['hello' => 'John']
];
//Change by difined key set
$outputArray = change_key($sampleArray, ['hello' => 'hi']);
//Output Array: ['hi' => 'world', 'nested' => ['hi' => 'John']];
//Change by callback
$outputArray = change_key($sampleArray, function($key, $value) {
return ucwords(key);
});
//Output Array: ['Hello' => 'world', 'Nested' => ['Hello' => 'John']];
I have been trying to solve this issue for a couple hours using recursive functions, but finally I realized that we don't need recursion at all. Below is my approach.
$search = array('key1','key2','key3');
$replace = array('newkey1','newkey2','newkey3');
$resArray = str_replace($search,$replace,json_encode($array));
$res = json_decode($resArray);
On this way we can avoid loop and recursion.
Hope It helps.