merge two array in one array - php

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.

Related

need to store values from fetched array into new array

i have a code like this
$table=table_name;
$sql="SELECT * from $table where student_id='X' and
class='Y' and section='Z'";
$result=$conn->query($sql);
while($row=mysqli_fetch_array($result)
{
$column[]=$row;
}
//printing $columns array
print_r($column);
output
ARRAY ( [0] => ARRAY ( [0] => 1 [SNO] => 1 [1] => 21DBAAACAC0 [STUDENT_ID] => 21DBAAACAC0 [2]
=> WEEKEND [EXAM_NAME] => WEEKEND [3] => 8TH-STANDARD [CLASS] => 8TH-STANDARD [4] =>
A [SECTION] => A [5] => 0 [PERCENTAGE] => 0 [6] => 2021-03-29 [CONDUCTED_DATE]
=> 2021-03-29 [7] => [TELUGU] => [8] => 35 [ENGLISH] => 35 [9] => [MATHEMATICS] => [10] =>
[SOCIAL] => [11] => [HINDI] => [12] => [SCIENCE] => [13] => [NATURAL SCIENCE] => ) )
i need to store column names in to an array like this
column[0]=sno;
column[1]=student_id;
column[2]=exan_name;
column[3]=class; and so on..
ultimately i need column names(of dynamically created table) into an array
use following code to get keys of associative array
<?php
$new = call_user_func_array('array_merge', 'array name here');
for($i=0;$i<sizeof($new)-1;$i++)
{
echo $new[$i]."<br>";
}
?>
it will give output
sno(column 1 name)
student_name(column 2 name)
student_id(column 3 name)...up to size-1
well you can use:
while ($row = $result->fetch_assoc()) {
//code here
}
you'll have an associative array like this:
$row(
"column_key0" => "column_value0",
"column_key1" => "column_value"
//and so on
);
then you can access it with a foreach
foreach ($row as $column_key => $value) {
//code here ($column_key is the name of your column)
};
then you can do what you want like save it in another array checking for duplicates or simply use it for your needs.
This way also if you don't know the table structure you can use column names.
so:
$result_set = $result->fetch_assoc();
foreach ($result_set as $row) { // here you can replace with as $row_number => $row if needed
foreach ($row as $column_key => $column_value){
//code here ($column_key is the name of your column)
}
};
is the final result;

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;

PHP delete array index through value

I'm trying to unset two specific array positions which contain two values.
My actual code to fill the array.
function get_store_list(){
$data = #file_get_contents('http://www.zwinky.com/xml/clothingList.xml');
$data = #simplexml_load_string($data);
$data = $data->xpath('//stores/store');
foreach($data as $store) {
$storeArray[] = array(
"name" => (string)$store['name'],
"id" => (string)$store['id']
);
}
return $storeArray;
}
$store = get_store_list();
The array looks like the following incase ill echo it out using print_r function:
Array
(
[0] => Array
(
[name] => Artizans
[id] => 20037336
)
[1] => Array
(
[name] => Bwabies!
[id] => 20080134
)
[2] => Array
(
[name] => Crave Mart
[id] => 20097365
)
[3] => Array
(
[name] => David & Goliath
[id] => 20099998
)
[4] => Array
(
[name] => Domo
[id] => 20098166
)
[5] => Array
(
[name] => Emily the Strange
[id] => 20101926
)
[6] => Array
(
[name] => Garfield
[id] => 20098167
)
[7] => Array
(
[name] => Jetsetter
[id] => 26
)
[8] => Array
(
[name] => Like Dat
[id] => 3
)
[9] => Array
(
[name] => Paris Hilton
[id] => 21
)
[10] => Array
(
[name] => Peppermint Place
[id] => 12
)
[11] => Array
(
[name] => Rocawear
[id] => 19
)
[12] => Array
(
[name] => ShoeBuy
[id] => 10
)
[13] => Array
(
[name] => Skelanimals
[id] => 20100198
)
[14] => Array
(
[name] => Snoop Dogg
[id] => 20
)
[15] => Array
(
[name] => SW&TH
[id] => 20096121
)
[16] => Array
(
[name] => The Castle
[id] => 1
)
[17] => Array
(
[name] => The Lair
[id] => 4
)
[18] => Array
(
[name] => The Mix
[id] => 923
)
[19] => Array
(
[name] => The Powerpuff Girls
[id] => 20098121
)
[20] => Array
(
[name] => The Surf Shop
[id] => 5
)
[21] => Array
(
[name] => Tie The Knot
[id] => 20076231
)
[22] => Array
(
[name] => tokidoki
[id] => 20099224
)
[23] => Array
(
[name] => University Club
[id] => 2
)
[24] => Array
(
[name] => Z Avenue
[id] => 6
)
[25] => Array
(
[name] => Z's Greetings
[id] => 20099506
)
)
Now $store does contain 2 array indexes which I have to delete. Which are the following ids: 21 and 20076231
I've been trying the following already:
Array search code without beeing success. Does anyone have a idea what I could try?
There are a handful different approaches for this simple issue. One of them could be using function array_filter():
/**
* #param array $list the list to process
* #param array $IDsToRemove the IDs of elements to remove from $list
* #return array a subset of $list that does not contain elements having 'id' in $IDsToRemove
*/
function removeFromArray(array $list, array $IDsToRemove)
{
return array_filter(
// Filter the input list...
$list,
// ... using a function...
function (array $item) use ($IDsToRemove) {
// ... that accepts an element if its "id" is not in $IDsToRemove
return ! in_array($item['id'], $IDsToRemove);
}
);
}
// Usage
$filteredStore = removeFromArray($store, array(21, 20076231));
Try this in your loop, this will not include in your array than no need to unset like this:
foreach($data as $store) {
if($store['id'] == '20076231')
continue;
$storeArray[] = array(
"name" => (string)$store['name'],
"id" => (string)$store['id']
);
}
If you need to unset an item from your array after it's been created, take a look at array_map.
First map your array to retrieve the index of each ID.
$map = array_map(function($item){ return $item['id']; }, $store);
Then get the index of your ID from the map (e.g. 21).
$index = array_search(21, $map);
Then remove with array_splice.
array_splice($store, $index, 1);
why not use directly the id in your $storeArray? And as it seems to be integer why do you force it to (string)?
Try this:
function get_store_list(){
$data = #file_get_contents('http://www.zwinky.com/xml/clothingList.xml');
$data = #simplexml_load_string($data);
$data = $data->xpath('//stores/store');
foreach($data as $store) {
$storeArray[(int)$store['id']] = array(
"name" => (string)$store['name']
);
}
return $storeArray;
}
// delete the keys you want
unset ($storeArray[21], $storeArray[20076231]);
// or if you have more ids to delete you can create a deleteArray
$deleteArray = array(2, 20076231);
foreach ($deleteArray as $toDelete){
unset($storeArray($toDelete);
}
One line code is cool but sometimes explicit code is preferable.
function filter_by_id(array $data, $id)
{
foreach ($data as $k => &$v) {
foreach ((array) $id as $i) {
if ($v['id'] === $i) {
$v = null;
}
}
}
// 'array_filter()' produces a new array without the null entries.
// 'array_values()' produces a new array with indexes without gaps.
return array_values(array_filter($data));
}
You can filter by one id at time
$store = filter_by_id($store, 21);
Or you can filter multiple ids at the same time:
$store = filter_by_id($store, [21, 20076231]);

Multidimensional Array with foreach + while

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);

list and count elements in array php

I have the following array and am trying to loop through it with php, generate a list of the "Type" and count how many. The Type is the key, but there will be unique values such as Call, To-do, Meeting, Proposal, etc. My goal is to have the following out put:
Call 2
To-do 1
Meeting 3
Proposal 4
The above are not the values that will be output from the following array, but I wanted you to have an idea of what I am trying to accomplish. Please help!
Array (
[0] => Array (
[0] => Call
[Type] => Call
[1] => fxxxx#xxxxentllc.com
[EmailAddress] => xxxxr#xxxxentllc.com
[2] => 3xxxx00
[Phone] => 31xxxx00
[3] => 31xxxx871
[MobilePhone] => 31xxxx871
[4] => 102795
[CustomerID] => 102795
[5] => Nortxxxxal
[Company] => Noxxxxal
[6] => Frank
[FirstName] => Frank
[7] => Syxxxxer
[LastName] => Sxxxxter
[8] => 3
[Priority] => 3
[9] => invite to Haxxxxales for lunch
[Details] => invite to Hafxxxxales for lunch
[10] => 4503
[ActivityID] => 4503
[11] => 05/23/13
[DueDate] => 05/23/13
)
[1] => Array (
[0] => To-do
[Type] => To-do
[1] => fsxxxxer#summxxxxntllc.com
[EmailAddress] => fsxxxxer#summixxxxtllc.com
[2] => 315xxxx000
[Phone] => 3154xxxx0
[3] => 315xxxx1
[MobilePhone] => 315xxxx1
[4] => 102795
[CustomerID] => 102795
[5] => Norxxxxl
[Company] => Norxxxxcal
[6] => Frxxxxk
[FirstName] => Fxxxxk
[7] => Sxxxxr
[LastName] => Syxxxxer
[8] => 3
[Priority] => 3
[9] => find out who contact is for xxxxdical center
[Details] => find out who contact is foxxxxcal center
[10] => 4504
[ActivityID] => 4504
[11] => 05/23/13
[DueDate] => 05/23/13
)
)
This should do it:
$type_counts = array_count_values(array_map(function($x) {return $x['Type'];}, $array));
The array_map will return an array containing all the Type elements, then array_count_values will count the number of each of these and return this as an associative array.
something along the lines of:
foreach ($array as $key => $value) {
if (isset($result[$key])) {
$result[$key]++;
} else {
$result[$key] = 1;
}
}
if it is a muldi-dimensional array, just put another for each in there but that should give you an idea
$types = array();
foreach($array as $item) {
isset(${$item['Type']}) ? ${$item['Type']}++ : ${$item['Type']} = 1;
if(!in_array($item['Type'], $types) {
$types[] = $item['Type'];
}
foreach($types as $type) {
echo "$type ${$type}\n";
}
I think you can loop in your array and count each occorrence
$Call = 0;
$To_do = 0;
$Meeting = 0;
$Proposal = 0;
foreach($array as $data)
{
if($data['Type'] == 'Call')
{
$Call++;
} else if($data['Type'] == 'To-do')
{
$To_do++;
} else if($data['Type'] == 'Meeting')
{
$Meeting++;
} else if($data['Type'] == 'Proposal')
{
$Proposal++;
}
}
In this way you will have stored in each variable $Call $To_do $Meeting $Proposal its relative count
you can use (array_count_values($array));
http://php.net/manual/en/function.array-count-values.php
This gives count of all the keys in an array.
If you want only for the specific keys then use foreach loop
The one Petros mentioned is the best way to do it.
I would do something along the lines of:
$your_array = /* Your Array */
$types_count = array();
foreach ($your_array as $type_array){
$types_count[$type_array['Type']]++;
}

Categories