PHP array and foreach - php

This is my current code:
$exceptions = array();
foreach ($rows as $row) {
$opens = $row['opens'];
$closes = $row['closes'];
$joined = array($opens, $closes);
$exception = join('-', $joined);
$exceptions[] = array (
$row['date'] => array($exception),
);
}
Which gives:
Array ( [0] => Array ( [06/09] => Array ( [0] => 01:00-22:00 ) ) [1] => Array ( [06/10] => Array ( [0] => 01:00-22:00 ) ) )
But I'm aiming for this because the plugin requires this form:
Array ( [06/09] => Array ( [0] => 01:00-22:00 ) [06/10] => Array ( [0] => 01:00-22:00 ) )
Is there a way to rearrange the array to achieve this?

// Assumptions
// 1. You have `$first_exception` within scope
// 2. You have `$rows` within scope
$exceptions = array();
foreach ($rows as $row) {
// Assumption: `$row` has key `date`
$exceptions[$row['date']] = array (
$first_exception
);
}

Try this:
$exceptions = array();
foreach ($rows as $row) {
$exceptions[$row['date']] = array ($first_exception);
}

You could try this code. And try to read about arrays http://php.net/manual/en/book.array.php
$exceptions = array();
foreach ($rows as $row) {
$exceptions[$row['date']][] = array($first_exception);
}

Related

Append new key to an existing array in an object

I have an existing JSON array:
stdClass Object
(
[set] => Array
(
[0] => stdClass Object
(
[name] => agenda
)
[1] => stdClass Object
(
[name] => first aid
)
)
)
I need to add a new key to it, so the final JSON result is something like this:
set: [{
name: 'agenda',
value: 'Agenda'
}, {
code: 'first aid',
value: 'First Aid'
}],
This is what I've done so far:
$result = array();
foreach ($data->set as $k => $row) {
$result['name'][$k] = $row->name;
$result['value'][$k] = ucwords($row->name);
}
But I have ended up with:
Array
(
[name] => Array
(
[0] => agenda
[1] => aid kit
)
[value] => Array
(
[0] => Agenda
[0] => First Aid
)
)
How can I merge the above so the name and value keys are in pair rather then being separate?
Update $row directly to modify your existing $data:
foreach ($data->set as $row) {
$row->value = ucwords($row->name);
}
To do it the way you are attempting:
$result = $data;
foreach ($data->set as $k => $row) {
$result->set[$k]->value = ucwords($row->name);
}
Notice, $row is an object.
Your try this
$result = array();
$count = 0;
foreach ($data->set as $k => $row) {
$result[$count]['name'] = $row->name;
$result[$count]['value'] = ucwords($row->name);
$count++;
}
result this
Array
(
[0] => stdClass Object
(
[name] => agenda
[value] => Agenda
)
[1] => stdClass Object
(
[name] => first aid
[value] => First Aid
)
)
If you want to modify your existing object, you can just set the value property directly.
foreach ($data->set as $row) {
$row->value = ucwords($row->name);
}
If you want to create a result without modifying your original object or leaving references to its internal objects, you can clone each of the internal objects and add the new properties to the cloned objects.
$result = array();
foreach ($data->set as $k => $row) {
$obj = clone $row;
$obj->value = ucwords($row->name);
$result[$k] = $obj;
}

How to get the difference of two multidimensional arrays in php?

I want to get the difference of two multidimensional arrys, e.g.,
First Array:
Array
(
[qtr_selected] => Array
(
[partner_q_m_p__2031] => Array
(
[0] => q1
[1] => q2
)
[partner_q_m_p__2032] => Array
(
[0] => q1
)
)
)
Second Array:
Array
(
[qtr_completed] => Array
(
[partner_q_m_p__2031] => Array
(
[0] => q1
)
)
)
how do i get the difference of array1 & array2 as given below:
Array
(
[qtr_final] => Array
(
[partner_q_m_p__2031] => Array
(
[0] => q2
)
[partner_q_m_p__2032] => Array
(
[0] => q1
)
)
)
Tried array_diff() function but not getting array1 as difference except array2, i want array1 after subtracting array2 from it.
Simply make a custom function like as
function check_diff($arr1, $arr2){
$check = (is_array($arr1) && count($arr1)>0) ? true : false;
$result = ($check) ? ((is_array($arr2) && count($arr2) > 0) ? $arr2 : array()) : array();
if($check){
foreach($arr1 as $key => $value){
if(isset($result[$key])){
$result[$key] = array_diff($value,$result[$key]);
}else{
$result[$key] = $value;
}
}
}
return $result;
}
$result['qtr_final'] = check_diff($a1['qtr_selected'],$a2['qtr_completed']);
print_r($result);
Try as below :
$a1 = Array
(
'qtr_selected' => Array
(
'partner_q_m_p__2031' => Array
(
'0' => 'q1',
'1' => 'q2',
),
'partner_q_m_p__2032' => Array
(
'0' => 'q1'
)
)
);
$a2 = Array
(
'qtr_completed' => Array
(
'partner_q_m_p__2031' => Array
(
'0' => 'q1'
)
)
);
$result['qtr_final'] = check_diff_multi($a1['qtr_selected'],
$a2['qtr_completed']);
print '<pre>';
print_r($result);
print '</pre>';
function check_diff_multi($array1, $array2){
$result = array();
foreach($array1 as $key => $val) {
if(isset($array2[$key])){
if(is_array($val) && $array2[$key]){
$result[$key] = check_diff_multi($val, $array2[$key]);
}
} else {
$result[$key] = $val;
}
}
return $result;
}
You can get difference of array1 and array2 by using this:
<?
// array 1
$array1['qtr_selected']['partner_q_m_p__2031'] = array('q1','q2');
$array1['qtr_selected']['partner_q_m_p__2032'] = array('q1');
// array 2
$array2['qtr_completed']['partner_q_m_p__2031'] = array('q1');
$removalArr = array();
foreach ($array2 as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
$removalArr = $value2; // get last value of removal array
}
}
$finalArr = array();
foreach ($array1 as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
// check difference if available,
// if difference available use array_diff else use normal.
$finalArr['qtr_final'][$key2] = (array_diff($value2,$removalArr) ? array_diff($value2,$removalArr) : $value2);
}
}
echo "<pre>";
print_r($finalArr);
?>
Result:
Array
(
[qtr_final] => Array
(
[partner_q_m_p__2031] => Array
(
[1] => q2
)
[partner_q_m_p__2032] => Array
(
[0] => q1
)
)
)

PHP - Modify an array during foreach loop

public function getUserList($user_id){
$list_query = "SELECT ACTUAL_USER_ID FROM TABLE WHERE USER_ID = ".$user_id." ";
$result = parent::queryresult($list_query);
return $result;
}
foreach ($result as $uresult){ //$result contains user_id
$userlist[] = $classObject->getUserList($uresult['USER_ID']);
}
The loop outouts below
Array
(
[0] => Array
(
[0] => Array
(
[ACTUAL_USER_ID] => 133
)
)
[1] => Array
(
[0] => Array
(
[ACTUAL_USER_ID] => 122
)
)
)
How can I remove nested arrays and make it like below
Array
(
[0] => Array
(
[ACTUAL_USER_ID] => 133
)
[1] => Array
(
[ACTUAL_USER_ID] => 122
)
)
Use brackets [] to access array's elements
foreach ($result as $uresult){ //$result contains user_id
$userlist[] = $classObject->getUserList($uresult['USER_ID'])[0];
}
Edit: on different/old version of PHP you need to put array into variable first:
foreach ($result as $uresult){ //$result contains user_id
$row = $classObject->getUserList($uresult['USER_ID']);
$userlist[] = $row[0];
}
Change foreach statement as below
foreach ($result as $uresult){ //$result contains user_id
$res = $classObject->getUserList($uresult['USER_ID']);
if(isset($res[0]))
$userlist[] = $res[0];
}

convert array into key value pairs

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];
}

Creating An Associative Multi Dimensional Array from loop in PHP

How can I create an array like the following in PHP from a database result set using a loop:
Array
(
[T] => Array
(
[0] => Array
(
[id] => 1
[name] => Timer
)
[1] => Array
(
[id] => 2
[name] => Tub
)
)
[P] => Array
(
[0] => Array
(
[id] => 3
[name] => Paper
)
[1] => Array
(
[id] => 4
[name] => Puppy
)
)
)
You will notice that the array keys are a letter, which is taken from the 'name' value in the result set. The loop will be something like this:
while($result = $db->fetch($query) {
$key = $result['name']{0};
// your answer :-)
}
I think something like this should do it:
$sql = 'SELECT id, name FROM table';
$result = mysql_query( $sql);
$answer = array();
while( $row = mysql_fetch_assoc( $result))
{
$answer[ strtoupper($row['name'][0]) ][] = $row;
}
mysql_free_result( $result);
var_dump( $answer);
OR, to be more specific (if your query is returning more columns than just id and name):
while( $row = mysql_fetch_assoc( $result))
{
$answer[ strtoupper($row['name'][0]) ][] = array(
'id' => $row['id'],
'name' => $row['name']
);
}
$indexArray = array(); // Array from Example
while($result = $db->fetch($query) {
$key = $result['name']{0};
if(!isset($indexArray[$key])) {
$indexArray[$key] = array();
}
array_push($indexArray[$key], $result);
}
$results = array();
while($result = $db->fetch($query)) {
$key = strtoupper($result['name'][0]);
if(!isset($results[$key]))
$results[$key] = array();
$results[$key][] = $result;
}

Categories