Multidimensional Array with foreach + while - php

I need to create a multidimensional array with a foreach loop and a while loop.
The first array contains this:
Array
(
[0] => 13-10-14
[1] => 13-10-15
[2] => 13-10-16
[3] => 13-10-17
[4] => 13-10-18
[5] => 13-10-19
)
I need to make it look like this:
Array
(
[0] => Array
(
[date] => 13-10-14
[id] => Array
(
[0] => 012643
[1] => 012667
[2] => 013362
[3] => 016169
[4] => 016839
[5] => 035288
[6] => 035369
[7] => 037664
[8] => 038979
[9] => 039014
[10] => 039036
[11] => 039505
)
)
)
The first array I do a foreach loop with the second I need to make while as it is a sql query.
Here is the code:
foreach ($rs as $results) {
$rowT = $db->query("SELECT id FROM users WHERE LIMIT 10");
while ($rsT = $db->fetch_assoc($rowT)) {
$results['id'][] = $rsT;
}
$l_array[] = $results;
}## Heading ##
print_r($l_array);
Is returning the error:
Fatal error: Can not use string offset to an array

If your $rs is this:
array([0] => 13-10-14
[1] => 13-10-15
[2] => 13-10-16
[3] => 13-10-17
[4] => 13-10-18
[5] => 13-10-19)
Your foreach() would set $results to: 13-10-15, 13-10-16, etc. I think that's your error, since those are strings, not arrays. How about this:
$final_array = array();
foreach ($rs as $results) {
$tmp_array = array('date'=>$results);
$rowT = $db->query("SELECT id FROM users WHERE LIMIT 10");
while ($rsT = $db->fetch_assoc($rowT)) {
$tmp_array['id'][] = $rsT;
}
$final_array[] = $tmp_array;
}## Heading ##
print_r($final_array);

Related

merge two array in one array

I have two array, $result and $social_result. I have to merge both tables. social_icons_id of $result matches id of $social_result. If match then show link of $result array otherwise blank.
I have an array
Array
(
[0] => Array
(
[social_icons_id] => 14
[link] => www.instagram.com
[edittemplate_id] => 218
[name] => Email
[image] => email.png
)
[1] => Array
(
[social_icons_id] => 16
[link] => www.instagram.com
[edittemplate_id] => 218
[name] => Blogger
[image] => blogger.png
)
)
Another is:
Array
(
[0] => Array
(
[id] => 13
[name] => Address
[image] => address.png
)
[1] => Array
(
[id] => 14
[name] => Email
[image] => email.png
)
[2] => Array
(
[id] => 15
[name] => Fax
[image] => fax.png
)
[3] => Array
(
[id] => 16
[name] => Text
[image] => text.png
)
[4] => Array
(
[id] => 17
[name] => Website
[image] => Website.png
)
)
Now I have to merge both table in one table like:
Array
(
[0] =>
[1] => www.instagram.com
[2] =>
[3] =>
[4] =>
[5] => www.instagram.com
[6] =>
[7] =>
[8] =>
[9] =>
[10] =>
[11] =>
[12] =>
[13] =>
[14] =>
[15] =>
[16] =>
)
id of both tables matches and make one table.
I tried-
$result = $obj->select_social_ids($id); // for first table
$social_result = $obj->show_social_icons(); // for second table
for($j=0;$j<count($social_result);$j++)
{
if(in_array($social_result[$j]['id'], $result)) { // search value in the array
$link[] = $result[$j]['link'];
}
else
{
$link[] = '';
}
}
But not working.
Depending on where you're getting this information from (e.g. a database table), doing this operation in SQL may make more sense.
That said, given the data and code you've provided, I think your in_array() check is incorrect, as it will only check the top level of $result. The 'social_icon_id' value that you seem to want to compare to $social_results[$j]['id'] is contained in a nested array within $result.
You could do something like this:
<?php
$results = $obj->select_social_ids($id);
$results_ids = array_map(
function ($result) { return $result['id']; },
$results
);
$results = array_combine($results_ids, $results);
$social_results = $obj->show_social_icons();
foreach ($social_results as $social_result) {
$id = $social_result['id'];
if (isset($results[$id])) {
$link[] = $results[$id]['link'];
}
else
{
$link[] = '';
}
}
If I understand your question correctly, you want to loop thru $social_result and compare ID to those keys in $result, maybe something like this will work.
$link = array();
foreach($social_result as $social){
$key = array_search($social['id'], array_column($result, 'social_icons_id'));
if($key != ''){
$link[] = $result[$key]['link'];
}else{
$link[] = '';
}
}
I tested this code and it works to do what I beliueve you are trying to accomplish
$a = array('social_icons_id' => '14','link' => 'www.instagram14.com','edittemplate_id' => '218','name' => 'Email','image' => 'email.png');
$b = array('social_icons_id' => '16','link' => 'www.instagram16.com','edittemplate_id' => '218','name' => 'Blogger','image' => 'blogger.png');
$result = array($a,$b);
$social_result = array(array('id'=>'14','name'=>'address0','image'=>'adress.png'),array('id'=>'15','name'=>'address1','image'=>'adress.png'), array('id'=>'16','name'=>'address2','image'=>'adress.png'),array('id'=>'17','name'=>'address3','image'=>'adress.png'),array('id'=>'18','name'=>'address4','image'=>'adress.png'),array('id'=>'19','name'=>'address5','image'=>'adress.png'));
$link = array();
foreach($social_result as $social){
$key = array_search($social['id'], array_column($result, 'social_icons_id'));
echo "<p> k ".$key;
if($key != ''){
$link[] = $result[$key]['link'];
}else{
$link[] = '';
}
}
print_r($link);
Simply you can create a simple left join query to generate a flat array containing social image links.
select social_image.link
from social_icons
left join social_image
on social_icons.id = social_image.social_icons_id
order by social_icons.id
But be carefully with array size limitation on php, therefore that needs a proper result limitation.
select social_image.link
from social_icons
left join social_image
on social_icons.id = social_image.social_icons_id
order by social_icons.id
limit 1000
Hope this helps.

Array subtraction in mysli_fetch_assoc

I have some sorting problem to this i want it to compare properly but the array result is incrementing
$query=mysqli_query($conn,"SELECT * FROM questions WHERE MATCH (question) AGAINST ('$msg*' IN BOOLEAN MODE) limit $limit ");
}
while($row = mysqli_fetch_assoc($query)){
$id = $row ["id"];
$question = $row ["question"];
$answer = $row ["answer"];
$words2 = explode(" ", cleanWords($question));
foreach($words2 as $word)
{
$stem = PorterStemmer::Stem($word);
if(!in_array($stem, $stop_words)) {
$stem_words[] = $stem;
}
}
print_r($stem_words);
echo "<br>";
}
}
Now my result set is incrementing like
Array ( [0] => What [1] => IT [2] => STAFF [3] => )
Array ( [0] => What [1] => IT [2] => STAFF [3] => [4] => what [5] => it [6] => )
Array ( [0] => What [1] => CEIT [2] => UCC [3] => [4] => what [5] => it [6] => [7] => Where [8] => it [9] => )
**I want to get the result like this
Array ( [0] => What [1] => IT [2] => STAFF [3] => )
Array ( [0] => what [1] => it [2] => )
Array ( [0] => Where [1] => it [2] => )
The problem is that you are just adding each word to the $stem_words array. Instead for each record, build a list of words for this record ($newList in this code) and add this record to the $stem_words array...
$newList = [];
foreach($words2 as $word)
{
$stem = PorterStemmer::Stem($word);
if(!in_array($stem, $stop_words)) {
$newList[] = $stem;
}
}
$stem_words[] = $newList;

how to array push with multidimension in php

I have an array in PHP loop output like this
this is my php code :
$sql = "SELECT * FROM `acc` ";
$stm = $conn->prepare($sql);
$stm->execute();
$array= [];
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$array[]=$row['h_id'];
}
print_r($array);
and output is :
Array
( [0] => 11
[1] => 12
[2] => 13
[3] => 1101
[4] => 1102
[5] => 110101
[6] => 110102
[7] => 1201
[8] => 1202
[9] => 1301
[10] => 1302
[11] => 1303
[12] => 130201
[13] => 130202
[14] => 130301
[15] => 130302
)
and I want to sort and rearrange array to multi-dimension for parent and child with php Loop Like this :
Array
(
[11] => Array
(
[1101] => Array
(
[0] => 110101
[1] => 110102
)
)
[12] => Array
(
[0] => 1201
[1] => 1202
)
[13] => Array
(
[0] => 1301
[1302] => Array
(
[0] => 130201
[1] => 130202
)
[1303] => Array
(
[0] => 130301
[1] => 130302
)
)
how to implemention and push array to another with php.
thanks!
I absolutely don't understand what you're doing, but I think I've grasped how your input may be mapped to desired output. Here is the code:
<?php
$flat = [
11,
12,
13,
1101,
1102,
110101,
110102,
1201,
1202,
1301,
1302,
1303,
130201,
130202,
130301,
130302,
];
function expand($flat)
{
$expanded = [];
foreach ($flat as $element) {
$sections = str_split((string)$element, 2);
$tmp = &$expanded;
$path = '';
foreach ($sections as $section) {
$path .= $section;
if (!isset($tmp[$path])) {
$tmp[$path] = [];
}
$tmp =& $tmp[$path];
}
unset($tmp);
}
return $expanded;
}
function fold($expanded) {
$folded = [];
foreach ($expanded as $key => $value) {
if ($value === []) {
$folded[] = $key;
} else {
$folded[$key] = fold($value);
}
}
return $folded;
};
print_r(fold(expand($flat)));
And here is its output (which is suspiciously close to yours):
Array
(
[11] => Array
(
[1101] => Array
(
[0] => 110101
[1] => 110102
)
[1102] => 1102
)
[12] => Array
(
[0] => 1201
[1] => 1202
)
[13] => Array
(
[0] => 1301
[1302] => Array
(
[0] => 130201
[1] => 130202
)
[1303] => Array
(
[0] => 130301
[1] => 130302
)
)
)
There are some differences, though, e.g. there is element 1102 in your input, but in your sample output it is absent, and I'm not sure if you forgot it or if you have filtered it out for some reason.

Remove identical values except first and last

I have a php script creating a multidimensional array:
$res = mysql_query("SELECT `date`, `temperature` FROM `general` ORDER BY `date`", $db);
$outside_temperature_array = array();
while($row = mysql_fetch_assoc($res)) {
$date = $row['date'];
$temperature = $row['temperature'];
$temp_array = array();
array_push($temp_array, $date);
array_push($temp_array, $temperature);
array_push($outside_temperature_array, $temp_array);
unset($temp_array);
}
print_r($outside_temperature_array);
The multidimensional array looks like this. It has a unix timestamp in sequential order along with a value.
Array
(
[0] => Array
(
[0] => 1452483001
[1] => 40
)
[1] => Array
(
[0] => 1452483301
[1] => 39
)
[2] => Array
(
[0] => 1452483600
[1] => 39
)
[3] => Array
(
[0] => 1452483901
[1] => 39
)
[4] => Array
(
[0] => 1452484201
[1] => 39
)
[5] => Array
(
[0] => 1452484502
[1] => 39
)
[6] => Array
(
[0] => 1452484801
[1] => 38
)
[7] => Array
(
[0] => 1452485101
[1] => 38
)
[8] => Array
(
[0] => 1452485400
[1] => 38
)
[9] => Array
(
[0] => 1452485701
[1] => 39
)
[10] => Array
(
[0] => 1452486002
[1] => 39
)
)
I want to omit all identical values except for the first and last, only when they show up sequentially. Think of this plotted on a line graph. I basically want to remove the unnecessary values that fall between two points of identical values. So the above array would change to this:
Array
(
[0] => Array
(
[0] => 1452483001
[1] => 40
)
[1] => Array
(
[0] => 1452483301
[1] => 39
)
[2] => Array
(
[0] => 1452484502
[1] => 39
)
[3] => Array
(
[0] => 1452484801
[1] => 38
)
[4] => Array
(
[0] => 1452485400
[1] => 38
)
[5] => Array
(
[0] => 1452485701
[1] => 39
)
[6] => Array
(
[0] => 1452486002
[1] => 39
)
)
You need to:
Keep track of the last temperature.
When a temperature change is detected, append the held row (if applicable) and the current row to the final array.
If there was no temperature change, hold the row as the last duplicate.
After the loop, append the held row to the final array if it is set.
This should work for you.
<?php
$res = mysql_query("SELECT `date`, `temperature` FROM `general` ORDER BY `date`", $db);
$outside_temperature_array = array();
$last_temp = null;
$held_row = null;
while($row = mysql_fetch_assoc($res)) {
// If we're on a new temperature
if ($row['temperature'] !== $last_temp) {
// Append and clear the held row first
if (is_array($held_row)) {
$outside_temperature_array[] = [$held_row['date'], $held_row['temperature']];
$held_row = null;
}
// Append this row and note the temperature
$outside_temperature_array[] = array($row['date'], $row['temperature']);
$last_temp = $row['temperature'];
} else {
// Hold the row in case the next row is different
$held_row = $row;
}
}
// If the last row was not appended to the array
if (is_array($held_row)) {
// Append the held row
$outside_temperature_array[] = array($held_row['date'], $held_row['temperature']);
}
print_r($outside_temperature_array);
$res = mysql_query("SELECT `date`, `temperature` FROM `general` ORDER BY `date`", $db);
$outside_temperature_array = array();
$oldTemperature = null;
while($row = mysql_fetch_assoc($res)) {
if($oldTemperature == $row['temperature'] && next($row)['temperature'] == $oldTemperature )
continue;
}
$oldTemperature = $row['temperature'];
$outside_temperature_array[] = array($row['date'],$row['temperature']);
}
print_r($outside_temperature_array);
You can try passed eqvivalent element in array use continue, but this code non testing. I think maybe you can execute sql query for this. And mysql this old extensions you need use PDO or Mysqli.

Combining arrays with common values

I have an array of dates that looks like this:
Array
(
[0] => '2014-01-01'
[1] => '2014-01-02'
[2] => '2014-01-03'
[3] => '2014-01-04'
[4] => '2014-01-05'
[5] => '2014-01-06'
[6] => '2014-01-07'
)
and I have another array of dates and counts that looks like this:
[All] => Array
(
[0] => Array
(
[count] => 2
[date] => 2014-01-06
)
[1] => Array
(
[count] => 1
[date] => 2014-01-03
)
[2] => Array
(
[count] => 43
[date] => 2013-12-11
)
[3] => Array
(
[count] => 103
[date] => 2013-12-10
)
[4] => Array
(
[count] => 128
[date] => 2013-12-09
)
[5] => Array
(
[count] => 75
[date] => 2013-12-08
)
[6] => Array
(
[count] => 107
[date] => 2013-12-07
)
I want to make a new associative array where all the keys are the dates from the first array above and all of the values are either the count matched up with the corresponding date or "0".
So for instance, the new array would look like this:
Array
(
[2014-01-01] => 0
[2014-01-02] => 0
[2014-01-03] => 1
[2014-01-04] => 0
[2014-01-05] => 0
[2014-01-06] => 2
[2014-01-07] => 0
)
Does that make sense? Please feel free to ask any questions you may have. Thank you!
Try this code:
$result = array();
foreach($firstArray as $f){
foreach($secondArray as $s){
if($s['date'] == $f) $result[$f] = $s['count'];
}
if(!array_key_exists($f, $result)) $result[$f] = 0;
}
$result = array();
foreach($secondArray as $s){
if(in_array($s['date'], $firstArray) {
unset($firstArray[$s['date']]);
$result[$s['date']] = $s['count'];
}
}
// if items left in first array that are not found within foreach:
if (!empty($firstArray))
$result = array_merge($result, array_fill_keys($firstArray, 0));
// sort by key so dates go ascending
ksort($result);
$new = array();
foreach($all as $row)
{
$new[$row['date']] = $row['count'];
}
array_merge ($new, $old);
Here $all is the array with the date and count indices.
$old is the exisisting array.
That's a 2-liner:
// use dates as index and set everything to 0
$result = array_fill_keys($x, 0));
// copy over existing counts
array_walk($all, function($v) use (&$result) { if (array_key_exists($v['date'], $result)) { $result[$v['date']] = $v['count'];}});

Categories