Looking to loop through an array of URLs and inject each keyword from a second array into each URL but can't get to grips with the understanding of arrays. Eg:
$key = array("Keyword+1", "Keyword+2", "Keyword+3"),
$url =array("google.co.uk/#hl=en&q=", "bing.com/search?q=","uk.search.yahoo.com/search?vc=&p="),
I'd like the above to output:
google.co.uk/#hl=en&q=Keyword+1
google.co.uk/#hl=en&q=Keyword+2
google.co.uk/#hl=en&q=Keyword+3
bing.com/search?q=Keyword+1
bing.com/search?q=Keyword+2
bing.com/search?q=Keyword+3
uk.search.yahoo.com/search?vc=&p=Keyword+1
uk.search.yahoo.com/search?vc=&p=Keyword+2
uk.search.yahoo.com/search?vc=&p=Keyword+3
Is there an efficient way to achieve this? :)
foreach($url as $currenturl)
{
foreach($key as $currentkey)
{
echo $currenturl . $currentkey . '\n';
}
}
try this
Here is how you can do that:
$keys = array("Keyword+1", "Keyword+2", "Keyword+3");
$urls =array("google.co.uk/#hl=en&q=", "bing.com/search?q=","uk.search.yahoo.com/search?vc=&p=");
$my_array = array();
foreach($urls as $url)
{
foreach($keys as $key)
{
$my_array[] = $url . $key;
}
}
print_r($my_array);
Result:
Array
(
[0] => google.co.uk/#hl=en&q=Keyword+1
[1] => google.co.uk/#hl=en&q=Keyword+2
[2] => google.co.uk/#hl=en&q=Keyword+3
[3] => bing.com/search?q=Keyword+1
[4] => bing.com/search?q=Keyword+2
[5] => bing.com/search?q=Keyword+3
[6] => uk.search.yahoo.com/search?vc=&p=Keyword+1
[7] => uk.search.yahoo.com/search?vc=&p=Keyword+2
[8] => uk.search.yahoo.com/search?vc=&p=Keyword+3
)
You first want to loop over the $url array, then for each item in the $url array, you also want to loop over all the keys in the $key array and append them to the item you picked from $url,
foreach ($url as $u)
{
foreach ($key as $k)
{
echo $u.$k."\n";
}
}
What you're describing is a generalization of the outer product.
It would be more interesting to define a higher order function for this:
/**
* A generalization of the outer product, forming all the possible
* combinations of the elements of the two arrays and feeding them
* to $f.
* The keys are disregarded
**/
function array_outer($f, array $array1, array $array2) {
$res = array();
foreach ($array1 as $e1) {
$cur = array();
foreach ($array2 as $e2) {
$cur[] = $f($e1, $e2);
}
$res[] = $cur;
}
return $res;
}
$f = function ($a,$b) { return $a.$b; };
print_r(array_outer($f, array("a","b","c"), array("1", "2", "3")));
gives:
Array
(
[0] => Array
(
[0] => a1
[1] => a2
[2] => a3
)
[1] => Array
(
[0] => b1
[1] => b2
[2] => b3
)
[2] => Array
(
[0] => c1
[1] => c2
[2] => c3
)
)
See Mathematica's Outer.
Related
In a foreach loop i would like to compare [name] value beetween different arrays but they have not the same levels.
Array(
[array1] => Array
(
[0] => WP_Term Object
(
[name] => Plafond
)
)
[array2] => WP_Term Object
(
[name] => Chaudière
)
[array3] => Array
(
[0] => WP_Term Object
(
[name] => Pla
)
[1] => WP_Term Object
(
[name] => Toc
)
)
)
I don't know how could i get the [name] in the same loop whereas levels are different.
I have tried to make :
foreach( $fields as $name => $value )
{
echo $value->name; }
Should i add another loop in the first loop ?
thanks
So your data looks like this:
$json = '{"array1":[{"name":"Plafond"}],"array2":{"name":"Chaudière"},"array3":[{"name":"Pla"},{"name":"Toc"}]}';
$array = json_decode($json);
If you don't know how deep it will go, a simple recursive function should work. Perhaps something like this:
function get_name($o, &$output) {
if (is_array($o)) {
foreach($o as $v) {
get_name($v, $output);
}
} elseif (property_exists($o, "name")) {
$output[] = $o->name;
}
}
$output = [];
foreach ($array as $v) {
get_name($v, $output);
}
If you data is going to look like the sample you provided (i.e. it will always be first or second level) then you don't need to worry about recursion.
$output = [];
foreach ($array as $k=>$v) {
if (is_array($v)) {
foreach ($v as $k2=>$v2) {
$output[] = $v2->name;
}
} else {
$output[] = $v->name;
}
}
Either way, your output values are all in the $output array:
print_r($output);
Output:
Array
(
[0] => Plafond
[1] => Chaudière
[2] => Pla
[3] => Toc
)
You can use array_map, array_key_exists to retrive the name index from the array
$jsonFormat = '{"array1":[{"name":"Plafond"}],"array2":{"name":"Chaudière"},"array3":[{"name":"Pla"},{"name":"Toc"}]}';
$jsonArray = json_decode($jsonFormat,true);
$res = [];
array_map(function($v) use (&$res){
if(array_key_exists('name', $v)){
$res[] = $v['name'];
}else{
foreach($v as $_key => $_value){
$res[] = $_value['name'];
}
}
}, $jsonArray);
echo '<pre>';
print_r($res);
Result:-
Array
(
[0] => Plafond
[1] => Chaudière
[2] => Pla
[3] => Toc
)
You can use $res to compare the names.
I have this array:
Array
(
[0] => Array
(
[0] => 1
[1] => a,b,c
)
[1] => Array
(
[0] => 5
[1] => d,e,f
)
)
I want the final array to be this:
Array
(
[0] => Array
(
[0] => 1
[1] => a
)
[1] => Array
(
[0] => 1
[1] => b
)
[2] => Array
(
[0] => 1
[1] => c
)
[3] => Array
(
[0] => 5
[1] => d
)
[4] => Array
(
[0] => 5
[1] => e
)
[5] => Array
(
[0] => 5
[1] => f
)
)
This is what I did:
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count] = $arr;
$temp[$count][1] = $row;
$count++;
}
}
print_r($temp);
?>
This totally works but I was wondering if there was a better way to do this. This can be very slow when I have huge data.
Try like this way...
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count][] = $arr[0];
$temp[$count][] = $row;
$count++;
}
}
/*print "<pre>";
print_r($temp);
print "<pre>";*/
?>
Here's a functional approach:
$result = array_merge(...array_map(function(array $a) {
return array_map(function($x) use ($a) {
return [$a[0], $x];
}, explode(",", $a[1]));
}, $array));
Try it online.
Or simply with two loops:
$result = [];
foreach ($array as $a) {
foreach (explode(",", $a[1]) as $x) {
$result[] = [$a[0], $x];
}
}
Try it online.
Timing these reveals that a simple loop construct is ~8 times faster.
functional: 4.06s user 0.08s system 99% cpu 4.160 total
loop: 0.53s user 0.05s system 102% cpu 0.561 total
If you need other way around,
$array = array(array(1, "a,b,c"), array(5, "d,e,f"));
$temp = [];
array_walk($array, function ($item, $key) use (&$temp) {
$second = explode(',', $item[1]);
foreach ($second as $v) {
$temp[] = [$item[0], $v];
}
});
print_r($temp);
array_walk — Apply a user supplied function to every member of an array
Here is working demo.
I have to arrays I would like to compare:
$original and $duplicate.
for example here is my original file:
print_r($original);
Array ( [0] => cat423 [1] => dog456 [2] => horse872 [3] => duck082 )
and here is my duplicate:
print_r($dublicate);
Array ( [0] => cat423 [1] => dug356 )
I compare them with array_diff:
$result = array_diff($original, $dublicate);
My result:
Array ( [1] => dog456 [2] => horse872 [3] => duck082 )
So far so good, but I need to make a difference between the values which are incorrect and the values which are completely missing. Is this possible?
A way would be to crawl the entire original array, afterwards you will have two arrays, missings and duplicates.
$original = array("cat423", "dog456", "horse872", "duck082");
$duplicate = array("cat423", "dug356");
$missings = $duplicates = array();
foreach ($original as $val) {
if (in_array($val, $duplicate))
$duplicates[] = $val;
else
$missings[] = $val;
}
If you need the keys as well, you would have to alter the foreach loop like so:
foreach ($original as $key=>$val) {
if (in_array($val, $duplicate))
$duplicates[] = array("key" => $key, "value" => $val);
else
$missings[] = array("key" => $key, "value" => $val);
}
use in_array function
$original = array("cat423", "dog456", "horse872", "duck082");
$duplicate = array("cat423", "dug356");
foreach ($original as $item) {
if(in_array($item, $duplicate))
{
$dup[] = $item;
}
else
{
$miss[] = $item;
}
}
print_r($miss); #Array ( [0] => dog456 [1] => horse872 [2] => duck082 )
print_r($dup); #Array ( [0] => cat423 )
Working Preview
I have an 2d array which returns me this values:
Array (
[0] => Array (
[0] => wallet,pen
[1] => perfume,pen
)
[1] => Array (
[0] => perfume, charger
[1] => pen,book
).
Out of this i would like to know if it is possible to create a function which would combine the array going this way,and create a new one :
if for example [0] => Array ( [0] => wallet,pen [1] => perfume,pen ) then should be equal to
[0] => Array ( [0] => wallet,pen, perfume ) because there is a common word else do nothing.
And also after that retrieve each words as strings for further operations.
How can i make the values of such an array unique. Array ( [0] => Array ( [0] => wallet [1] => pen [2] => perfume [3] => pen) ) as there is pen twice i would like it to be deleted in this way ( [0] => Array ( [0] => wallet [1] => pen [2] => perfume) )
It's just a matter of mapping the array and combining the inner arrays:
$x = [['wallet,pen', 'perfume,pen'], ['perfume,charger', 'pen,book']];
$r = array_map(function($item) {
return array_unique(call_user_func_array('array_merge', array_map(function($subitem) {
return explode(',', $subitem);
}, $item)));
}, $x);
Demo
This first splits all the strings based on comma. They are then merged together with array_merge() and the duplicates are removed using array_unique().
See also: call_user_func_array(), array_map()
Try this :
$array = Array (Array ( "wallet,pen", "perfume,pen" ), Array ( "perfume, charger", "pen,book" ));
$res = array();
foreach($array as $key=>$val){
$temp = array();
foreach($val as $k=>$v){
foreach(explode(",",$v) as $vl){
$temp[] = $vl;
}
}
if(count(array_unique($temp)) < count($temp)){
$res[$key] = implode(",",array_unique($temp));
}
else{
$res[$key] = $val;
}
}
echo "<pre>";
print_r($res);
output :
Array
(
[0] => wallet,pen,perfume
[1] => Array
(
[0] => perfume, charger
[1] => pen,book
)
)
You can eliminate duplicate values while pushing them into your result array by assigning the tag as the key to the element -- PHP will not allow duplicate keys on the same level of an array, so any re-encountered tags will simply be overwritten.
You can use recursion or statically written loops for this task.
Code: (Demo)
$result = [];
foreach ($array as $row) {
foreach ($row as $tags) {
foreach (explode(',', $tags) as $tag) {
$result[$tag] = $tag;
}
}
}
var_export(array_values($result));
Code: (Demo)
$result = [];
array_walk_recursive(
$array,
function($v) use(&$result) {
foreach (explode(',', $v) as $tag) {
$result[$tag] = $tag;
}
}
);
var_export(array_values($result));
I am Having an mutidimensional array getting result like given below
Array
(
[0] => Array
(
[0] => 70
)
[1] => Array
(
[0] => 67
)
[2] => Array
(
[0] => 75
[1] => 73
[2] => 68
)
[3] => Array
(
[0] => 68
)
[4] => Array
(
[0] => 76
)
)
But I need to convert it to single array
And I want to convert in to single dimensional array as
Array
(
[0] => 70
[1] => 67
[2] => 75
[3] => 73
[4] => 68
[5] => 68
[6] => 76
)
How to convert it using php functions?
Or Is there any other way to do it?
You can try
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
$l = iterator_to_array($it, false);
var_dump($l); // one Dimensional
Try with:
$input = array(/* your array*/);
$output = array();
foreach ( $input as $data ) {
$output = array_merge($output, $data);
}
You can use array_walk_recursive() for that coupled with a closure:
$res = array(); // initialize result
// apply closure to all items in $data
array_walk_recursive($data, function($item) use (&$res) {
// flatten the array
$res[] = $item;
});
print_r($res); // print one-dimensional array
This should do the trick
$final = array();
foreach ($outer as $inner) {
$final = array_merge($final, $inner);
}
var_dump($final);
Or you could use array_reduce() if you have PHP >= 5.3
$final = array_reduce($outer, function($_, $inner){
return $_ = array_merge((array)$_, $inner);
});
var_dump($final);
For a more generic function which can deal with multidimensional arrays, check this function,
function arrayFlattener($input = array(), &$output = array()) {
foreach($input as $value) {
if(is_array($value)) {
arrayFlattener($value, $output);
} else {
$output[] = $value;
}
}
}
You can find an example here.
By using this function you can convert any dimension array into a single dimention array.
$result = array();
$data = mearchIntoarray($result,$array);
function mearchIntoarray($result,$now)
{
global $result;
foreach($now as $key=>$val)
{
if(is_array($val))
{
mearchIntoarray($result,$val);
}
else
{
$result[] = $val;
}
}
return $result;
}
Where $array is your given array value.