This is my code! I'm trying to get from $test array and at end show me like $final array! tnx to help! code should get domain name and show how many time a userid has been repeated!
<?php
$test = array(
array(
'id' => 1,
'domain' => 'google.com',
'userid' => "123"
),
array(
'id' => 2,
'domain' => 'google.com',
'userid' => "456"enter
),
array(
'id' => 3,
'domain' => 'yahoo.com',
'userid' => "456"
),
array(
'id' => 4,
'domain' => 'google.com',
'userid' => "123"
),
array(
'id' => 5,
'domain' => 'bing.com',
'userid' => "128"
)
);
$i=0;
foreach ($test as $items) {
$domains[$i]=$items['domain'];
$userid[$i]=$items['userid'];
$i++;
}
$domain=array_unique($domains);
$domain1 = array_values($domain);
print_r($domain);
echo '<pre>';
print_r($test);
echo '</pre>';
echo '<hr>';
$d=1; $tedad = 1;
while($d<=4){
$b = 1 ; $c=0;
while ($test[$b]['id']<=4) {
if($test[$b]['domain'] == $domain1[$d])
{
$temp = $test[$b]['userid'];
if(/*$test[$b]['userid'] !==*/ !array_key_exists($domain1[$d] ['userid']){
//$domain1[$d] = array($test[$b]['userid'] => $tedad) ;
echo $temp;
$end = array(
$domain1[$d] => array(
$temp => $tedad )
);
}
else{
$end[$d][$test[$b]['userid']]= $end[$d][$test[$b]['userid']] +1;
}
}
else{
$b++;
}
}
$d++; $tedad = 1;
}
print_r($end);
$final = array(
"google.com" => array(
"123" => 2,
"456" => 1
),
"yahoo.com" => array(
"456" => 1
)
);
echo '<pre>';
print_r($final);
echo '</pre>';
echo '<hr>';
?>
Try:
$result = array();
foreach($test as $t)
{
if(isset($result[$t['domain']][$t['userid']]))
$result[$t['domain']][$t['userid']]++;
else $result[$t['domain']][$t['userid']] = 1;
}
If you don't want to include some domains use like:
$result = array();
foreach($test as $t)
{
if($t['domain'] == 'bing.com')
continue;
if(isset($result[$t['domain']][$t['userid']]))
$result[$t['domain']][$t['userid']]++;
else $result[$t['domain']][$t['userid']] = 1;
}
<?php
$test = array(
array(
'id' => 1,
'domain' => 'google.com',
'userid' => "123"
),
array(
'id' => 2,
'domain' => 'google.com',
'userid' => "456"
),
array(
'id' => 3,
'domain' => 'yahoo.com',
'userid' => "456"
),
array(
'id' => 4,
'domain' => 'google.com',
'userid' => "123"
)
);
echo '<pre>';
print_r($test);
echo '</pre>';
echo '<hr>';
$domains = array();
foreach ($test as $value) {
if (!in_array($value['domain'], $domains))
$domains[$value['domain']] = array();
}
foreach ($domains as $key => $domain) {
foreach ($test as $item) {
if ($key == $item['domain']) {
if (isset($domains[$key][$item['userid']])) {
$domains[$key][$item['userid']] = $domains[$key] [$item['userid']]+1;
} else {
$domains[$key][$item['userid']] = 1;
}
}
}
}
echo '<pre>';
print_r($domains);
echo '</pre>';
echo '<hr>';
// $final = array(
// "google.com" => array(
// "123" => 2,
// "456" => 1
// ),
// "yahoo.com" => array(
// "456" => 1
// )
// );
// echo '<pre>';
// print_r($final);
// echo '</pre>';
// echo '<hr>';
?>
Related
I have an array as
$apps = array(
array(
'id' => '2',
'name' => 'Popcorn'
),
array(
'id' => '1',
'name' => 'EveryCord'
),
array(
'id' => '2',
'name' => 'AirShou'
),
Here I want to print names where id="2". So I tried it with following code.
foreach ( $apps as $var ) if ($var['id'] == "2") {
echo $var['name']
}
The problem is that it only print first result of the array as
"Popcorn".
But I want to extract all result which are
"Popcorn and Airshou"
How can I fix this. Can someone help me !
Try this;
$apps = [
['name' => 'Fish', 'id' => 2],
['name' => 'Chips', 'id' => 1],
['name' => 'Sticks', 'id' => 2],
];
$using = [];
foreach ( $apps as $var ) {
if ($var['id'] == "2") {
$using[] = $var['name'];
}
}
echo implode(" and ", $using);
RESULT:
You can create a sample array.
And append the name to it, if it is id=2
Code:
$apps = [
['id' => '2', 'name' => 'Popcorn'],
['id' => '1', 'name' => 'EveryCord'],
['id' => '2', 'name' => 'AirShou']
];
$names = [];
if (! empty($apps)) {
foreach ($apps as $elem) {
if ($elem['id'] == 2) {
$names[] = $elem['name'];
}
}
}
$finalName = ! empty($names) ? implode(' and ', $names) : '';
echo '<pre>';print_r($finalName);echo '</pre>';
// Output: Popcorn and AirShou
You can filter the array on the item id and then retrieve the column name:
array_column(array_filter($apps, function($v){return '2' === $v['id'];}), 'name')
result:
array(2) {
[0] =>
string(7) "Popcorn"
[1] =>
string(7) "AirShou"
}
Change your loop by this code, and you will got both names,
foreach ( $apps as $var ){
if ($var['id'] == "2") {
echo $var['name'];
}
}
Just grab names in array then implode it like this:
$temp = array();
foreach ( $apps as $var ) if ($var['id'] == "2") {
$temp[] = $var['name']
}
echo implode(' and ', $temp);
I wanted to refrain from using nested foreach in my actual code, so I was thinking of using an array function (correct me if I'm wrong) called array_walk thinking it would replace my code in foreach.
I wanted to compare both of the WHOLE array if they one of them have the same description, but the problem is array_walk only compares the first key/index and does not go through the second index to check. is there other way? I'm just trying to optimize my code
By the way, this code returns both found
<?php $array = array (
'1' => array(
'count' => '1',
'id' => 1,
'description' => 'Bag',
),
'2' => array(
'count' => '1',
'id' => 2,
'description' => 'Pencil',
), );
$bin = array (
'1' => array(
'count' => '1',
'id' => 2,
'description' => 'Bag',
),
'2' => array(
'count' => '1',
'id' => 2,
'description' => 'Pencil',
), );
$b = array_map(function($array, $bin) {
if ($array['description'] == $bin['description']){
$count = "found";
}else{
$count = "not found";
}
return array("status" => $count, "cart_array" => $array['description'], "bin"=>$bin['description']); }, $array, $bin);
var_dump($b);
?>
but this one, the first array doesnt return found, it should return
found because there is a pencil and bag in $bin array updated the code
<?php
$array = array (
'1' => array(
'count' => '1',
'id' => 1,
'description' => 'Bag',
),
'2' => array(
'count' => '1',
'id' => 2,
'description' => 'Pencil',
),
);
$bin = array (
'1' => array(
'count' => '1',
'id' => 2,
'description' => 'Pencil',
),
'2' => array(
'count' => '1',
'id' => 2,
'description' => 'Bag',
),
);
$b = array_map(function($array, $bin)
{
if ($array['description'] == $bin['description']){
$count = "found";
}else{
$count = "not found";
}
return array("status" => $count, "cart_array" => $array['description'], "bin"=>$bin['description']);
}, $array, $bin);
var_dump($b);
?>
Use array_column first to get all of description keys from $array. Then, you can check these values with $bin values.
$desc = array_column($array, 'description');
$b = array_map(function($array, $bin)
{
global $desc;
if (in_array($bin['description'], $desc)){
$count = "found";
}else{
$count = "not found";
}
return array("status" => $count, "cart_array" => $array['description'], "bin" => $bin['description']);
}, $array, $bin);
var_dump($b);
You don't have any expected output in the question but I assume you want to know the difference between them.
In the manual for array_diff there is a code called arrayRecursiveDiff which handles multidimensional arrays and outputs the difference.
var_dump(arrayRecursiveDiff($array, $bin));
function arrayRecursiveDiff($aArray1, $aArray2) {
$aReturn = array();
foreach ($aArray1 as $mKey => $mValue) {
if (array_key_exists($mKey, $aArray2)) {
if (is_array($mValue)) {
$aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);
if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
} else {
if ($mValue != $aArray2[$mKey]) {
$aReturn[$mKey] = $mValue;
}
}
} else {
$aReturn[$mKey] = $mValue;
}
}
return $aReturn;
}
This outputs:
array(2) {
[1]=>
array(2) {
["id"]=>
int(1)
["description"]=>
string(3) "Bag"
}
[2]=>
array(1) {
["description"]=>
string(6) "Pencil"
}
}
You can use this.Nevertheless both arrays have different length or the values do not have the same position, This will work :
$bin_desc=array_column($bin,'description');
$b = array_map(function($array)use($bin_desc) {
if (in_array($array['description'],$bin_desc)){
$count = "found";
}else{
$count = "not found";
}
return array("status" => $count, "cart_array" => $array['description'], "bin"=>$array['description']); }, $array);
var_dump($b);
I have an array of TLDs and prices, and now I want to be able to add a classification i.e. 'Australian','New Zealand','Industry' to the domains but I am having troubles adding the extra dimension.
The array I have is
$domains = array(
'.com.au' => '19.98',
'.melbourne' => '90.00',
'.academy' => '45.00',
'.accountants' => '120.00',
'.ac.nz' => '36.75');
$domains = array(
'.com.au' => array(
'country' => 'Australia',
'sector' => 'Industry',
'price' => '19.98'
),
);
Is this a beginning on what you're looking for ?
Is this code ok for you?
<?php
$domains = array(
'.com.au' => '19.98',
'.melbourne' => '90.00',
'.academy' => '45.00',
'.accountants' => '120.00',
'.ac.nz' => '36.75');
$newDomains = [];
foreach($domains as $key=>$value){
if($key == '.com.au'){
$newDomains[$key]['TLD'] = $value;
$newDomains[$key]['Industry'] = 'blabal';
}else{
$newDomains[$key] = $value;
}
}
echo '<pre>';
var_dump($newDomains);
echo '</pre>';
?>
Or even:
$domains = array(
'.com.au' => '19.98',
'.melbourne' => '90.00',
'.academy' => '45.00',
'.accountants' => '120.00',
'.ac.nz' => '36.75');
$industryArray = array(
'.com.au' => 'blabla'
);
$newDomains = [];
foreach($domains as $key=>$value){
if(isset($industryArray[$key])){
$newDomains[$key]['TLD'] = $value;
$newDomains[$key]['Industry'] = $industryArray[$key];
}else{
$newDomains[$key] = $value;
}
}
echo '<pre>';
var_dump($newDomains);
echo '</pre>';
The result is:
array(5) {
[".com.au"]=>
array(2) {
["TLD"]=>
string(5) "19.98"
["Industry"]=>
string(6) "blabla"
}
[".melbourne"]=>
string(5) "90.00"
[".academy"]=>
string(5) "45.00"
[".accountants"]=>
string(6) "120.00"
[".ac.nz"]=>
string(5) "36.75"
}
I have two arrays
$Array_1 = array(
'ID_1' => 'Michael',
'ID_2' => 'Jerry',
'ID_3' => 'Tony',
'ID_4' => 'Roger',
);
$Array_2 = array(
'ID_1' => 'Chef',
'ID_2' => 'Mechanic',
'ID_3' => 'Cook',
'ID_4' => 'Dealer',
);
I wish to merge them on the ID column and have my final array be in this form
$employees = array(
array(
'name' => 'Jason',
'occupation' => 'Chef'
),
array(
'name' => 'Mike',
'occupation' => 'Mechanic'
),
...
);
I know I can array combine them like below:
$new_array = array_combine(array_values($Array_1), array_values($Array_2));
but how would I add the titles "Name": and "Occupation":
Can you try this,
$Employees = array();
foreach($Array_1 as $key=>$value):
$Employees['Employees'][] = array('Name'=>$value, 'Occupation'=>$Array_2[$key]);
endforeach;
echo "<pre>";
print_r($Employees);
echo "</pre>";
echo json_encode($Employees);
OP:
{"Employees":[{"Name":"Jason","Occupation":"Chef"}, {"Name":"Mike","Occupation":"Mechanic"}]}
i dont know how the array look. but you can try my two solution
First solution
$array1 = array("id" => array("id1", "id2", "id3"), "names" => array("name1", "name2", "name3"));
$array2 = array("id" => array("id1", "id2", "id3"), "occupation" => array("occupation1", "occupation2", "occupation3"));
$filter_array = array("employees" => array());
foreach ($array1["id"] as $index => $key) {
$employee = array();
$occupation = in_array($key, $array2["id"]) ? $array2["occupation"][$index] : false;
if ($occupation === false) {
continue;
}
$employee["name"] = $key;
$employee["occupation"] = $occupation;
array_push($filter_array["employees"], $employee);
}
echo "<pre>" . print_r($filter_array, true) . "</pre>";
Second Solution
$array1 = array("id1" => array("names" => "name1"), "id2" => array("names" => "name2"), "id3" => array("names" => "name3"));
$array2 = array("id1" => array("occupation" => "occupation1"), "id2" => array("occupation" => "occupation2"), "id3" => array("occupation" => "occupation3"));
$filter_array = array("employees" => array());
foreach ($array1 as $key => $value) {
$employee = array();
if (!isset($array2[$key])) {
continue;
}
$employee["name"] = $value["names"];
$employee["occupation"] = $array2[$key]["occupation"];
array_push($filter_array["employees"], $employee);
}
echo "<pre>" . print_r($filter_array, true) . "</pre>";
i hope my code can help.
you can try this
$Array_1 = array(
'ID_1' => 'Michael',
'ID_2' => 'Jerry',
'ID_3' => 'Tony',
'ID_4' => 'Roger',
);
$Array_2 = array(
'ID_1' => 'Chef',
'ID_2' => 'Mechanic',
'ID_3' => 'Cook',
'ID_4' => 'Dealer',
);
$filter_array = array("employees" => array());
foreach($Array_1 as $key => $value){
$employee = array();
if(!isset($Array_2[$key])){ continue; }
$employee["name"] = $value;
$employee["occupation"] = $Array_2[$key];
array_push($filter_array["employees"], $employee);
}
EDIT 2
Aah, now I see the phpfiddle in the comments and the edit to the OP. So, the ID is already the key of the array? ... Then just do
foreach($Array_1 as $key_1 => $value_1) {
$new_Array[$key_1]['Names'] = $Array_1['Names'];
}
foreach($Array_2 as $key_2 => $value_2) {
$new_Array[$key_2]['Occupation'] = $Array_2['Occupation'];
}
use array_walk . It runs a function per each array item .combine them in the function .
Example Array:
$array = array([key1] =>
array([key11] =>
array([key111] => 'value111',
[key112] => 'value112',
[key113] => 'value113',
[key114] => array(A,B,C,D),
),
),
);
I need an output as below array:
array([key1/key11/key111] => 'value111',
[key1/key11/key112] => 'value112',
[key1/key11/key113] => 'value113',
[key1/key11/key114] => 'A,B,C,D' );
and i have tried using this function,
function listArrayRecursive($someArray, &$outputArray, $separator = "/") {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($someArray), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $k => $v) {
if (!$iterator->hasChildren()) {
for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) {
$p[] = $iterator->getSubIterator($i)->key();
}
$path = implode($separator, $p);
$outputArray[] = $path;
}
}
}
$outputArray = array();
listArrayRecursive($array, $outputArray);
I cant able to find how to achieve this by using the above function for "key1/key11/key114" getting value as i expected. Please help me on this.
Input:
$array = array(
'key1' => array(
'key11' => array(
'key111' => 'value111',
'key112' => 'value112',
'key113' => 'value113',
'key114' => array('A','B','C','D'),
),
'key12' => array(
'key121' => 'value121',
'key122' => 'value122',
'key123' => 'value123',
'key124' => array('A','B','C','D'),
),
),
'key2' => array(
'key21' => array(
'key211' => 'value111',
'key212' => 'value112',
'key213' => 'value113',
'key214' => array('A','B','C','D'),
),
),
);
Script:
function remap_keys($input, $max_depth, $separator = '/', /* reserved */ $keychain = array(), /* reserved */ &$output = array())
{
foreach ($input as $key => $element)
{
$element_keychain = array_merge($keychain, (array)$key);
if (($max_depth > 1) && is_array($element))
remap_keys($element, $max_depth -1, $separator, $element_keychain, $output);
else
$output[implode($separator, $element_keychain)] = implode(',', (array)$element);
}
return $output;
}
$array = remap_keys($array, 3);
print_r($array);
Output:
Array
(
[key1/key11/key111] => value111
[key1/key11/key112] => value112
[key1/key11/key113] => value113
[key1/key11/key114] => A,B,C,D
[key1/key12/key121] => value121
[key1/key12/key122] => value122
[key1/key12/key123] => value123
[key1/key12/key124] => A,B,C,D
[key2/key21/key211] => value111
[key2/key21/key212] => value112
[key2/key21/key213] => value113
[key2/key21/key214] => A,B,C,D
)
http://ideone.com/pqH45h
$array = array('key1' =>
array('key11' =>
array('key111' => 'value111',
'key112' => 'value112',
'key113' => 'value113',
'key114' => array(A,B,C,D),
),
),
);
function implode_arr_keys($array, $output_arr = array(), $cur_key = FALSE) {
foreach($array as $key => $value) {
if(is_array($value)) {
return implode_arr_keys($value, $output_arr, ($cur_key == FALSE ? $key : $cur_key.'/'.$key));
} else {
if(!is_numeric($key))
$output_arr[$cur_key.'/'.$key] = $value;
else
$output_arr[$cur_key] = $array;
}
}
return $output_arr;
}
print_r($array);
print_r(implode_arr_keys($array));