Manipulation of php array - php

I need to create path structure, with the values that I am getting from the array:
Array
(
[machineAttribute] => Array
(
[0] => TTT 1000 S
[1] => TTT 1100 S
)
[technicalAttribute] => Array
(
[0] => Certificate
[1] => Software
)
[languageAttribute] => Array
(
[0] => English
[1] => Spanish
)
)
So, I need to create path that looks like this:
Array
(
[0] => TTT 1000 S/Certificate/English
[1] => TTT 1000 S/Certificate/Spanish
[2] => TTT 1000 S/Software/English
[3] => TTT 1000 S/Software/Spanish
[4] => TTT 1100 S/Certificate/English
[5] => TTT 1100 S/Certificate/Spanish
[6] => TTT 1100 S/Software/English
[7] => TTT 1100 S/Software/Spanish
)
This is a perfect scenario and I was able to solve this with nested foreach:
if (is_array($machineAttributePath))
{
foreach ($machineAttributePath as $machinePath)
{
if (is_array($technicalAttributePath))
{
foreach ($technicalAttributePath as $technicalPath)
{
if (is_array($languageAttributePath))
{
foreach ($languageAttributePath as $languagePath)
{
$multipleMachineValuesPath[] = $machinePath . '/' . $technicalPath . '/' . $languagePath);
}
}
}
}
}
return $multipleMachineValuesPath;
}
But, the problem begins, if the array returns mixed values, sometimes, single value, sometimes array. For example:
Array
(
[machineAttribute] => Array
(
[0] => TTT 1000 S
[1] => TTT 1100 S
[2] => TTT 1200 S
)
[technicalAttribute] => Certificate
[languageAttribute] => Array
(
[0] => English
[1] => Spanish
)
)
Then the array should look like:
Array
(
[0] => TTT 1000 S/Certificate/English
[1] =>TTT 1000 S/Certificate/Spanish
[2] => TTT 1100 S/Certificate/English
[3] => TTT 1100 S/Certificate/Spanish
)
I wrote code, but it is really messy and long and not working properly. I am sure that this could be somehow simplified but I have enough knowledge to solve this. If someone knows how to deal with this situation, please help. Thank you.

You can convert any single value to array just by
(array) $val
In the same time, if $val is already array, it will be not changed
So, you can a little change all foreach
foreach((array) $something....

If you need something simple, you can convert your scalar values to array by writing simple separate function (let name it "force_array"). The function that wraps argument to array if it is not array already.
function force_array($i) { return is_array($i) ? $i : array($i); }
//...
foreach (force_array($machineAttributePath) as $machinePath)
{
foreach (force_array($technicalAttributePath) as $technicalPath)
{
foreach (force_array($languageAttributePath) as $languagePath)
{
$multipleMachineValuesPath[] = $machinePath . '/' . $technicalPath . '/' . $languagePath;
}
}
}
return($multipleMachineValuesPath);

You can do this way also without messing up. Just create the Cartesian of your input array and finally implode the generated array with /. Hope this helps :)
<?php
function cartesian($input) {
$result = array();
while (list($key, $values) = each($input)) {
if (empty($values)) {
continue;
}
if (empty($result)) {
foreach($values as $value) {
$result[] = array($key => $value);
}
}
else {
$append = array();
foreach($result as &$product) {
$product[$key] = array_shift($values);
$copy = $product;
foreach($values as $item) {
$copy[$key] = $item;
$append[] = $copy;
}
array_unshift($values, $product[$key]);
}
$result = array_merge($result, $append);
}
}
return $result;
}
$data = array
(
'machineAttribute' => array
(
'TTT 1000 S',
'TTT 1100 S'
),
'technicalAttribute' => array
(
'Certificate',
'Software'
),
'languageAttribute' => array
(
'English',
'Spanish',
)
);
$combos = cartesian($data);
$final_result = [];
foreach($combos as $combo){
$final_result[] = implode('/',$combo);
}
print_r($final_result);
DEMO:https://3v4l.org/Zh6Ws

This will solve your problem almost.
$arr['machineAttribute'] = (array) $arr['machineAttribute'];
$arr['technicalAttribute'] = (array) $arr['technicalAttribute'];
$arr['languageAttribute'] = (array) $arr['languageAttribute'];
$machCount = count($arr['machineAttribute']);
$techCount = count($arr['technicalAttribute']);
$langCount = count($arr['languageAttribute']);
$attr = [];
for($i=0;$i<$machCount;$i++) {
$attr[0] = $arr['machineAttribute'][$i] ?? "";
for($j=0;$j<$techCount;$j++) {
$attr[1] = $arr['technicalAttribute'][$j] ?? "";
for($k=0;$k<$langCount;$k++) {
$attr[2] = $arr['languageAttribute'][$k] ?? "";
$pathArr[] = implode('/',array_filter($attr));
}
}
}
print_r($pathArr);

This works too!
$results = [[]];
foreach ($arrays as $index => $array) {
$append = [];
foreach ($results as $product) {
foreach ($array as $item) {
$product[$index] = $item;
$append[] = $product;
}
}
$results = $append;
}
print_r(array_map(function($arr){ return implode('/',$arr);},$results));

Related

Explode array's data and make new array

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.

How to get the value from serialized array by using preg_match in php

I need to get the value from the serialized array by matching the index value.My unserialized array value is like
Array ( [info1] => test service [price_total1] => 10
[info2] => test servicing [price_total2] => 5 )
I need to display array like
Array ( [service_1] => Array ([info]=>test service [price_total] => 10 )
[service_2] => Array ([info]=>test servicing [price_total] => 5 ))
buy i get the result like the below one
Array ( [service_1] => Array ( [price_total] => 10 )
[service_2] => Array ( [price_total] => 5 ) )
my coding is
public function getServices($serviceinfo) {
$n = 1;
$m = 1;
$matches = array();
$services = array();
print_r($serviceinfo);
if ($serviceinfo) {
foreach ($serviceinfo as $key => $value) {
if (preg_match('/info(\d+)$/', $key, $matches)) {
print_r($match);
$artkey = 'service_' . $n;
$services[$artkey] = array();
$services[$artkey]['info'] = $serviceinfo['info' . $matches[1]];
$n++;
}
if ($value > 0 && preg_match('/price_total(\d+)$/', $key, $matches)) {
print_r($matches);
$artkey = 'service_' . $m;
$services[$artkey] = array();
$services[$artkey]['price_total'] = $serviceinfo['price_total' . $matches[1]];
$m++;
}
}
}
if (empty($services)) {
$services['service_1'] = array();
$services['service_1']['info'] = '';
$services['service_1']['price_total'] = '';
return $services;
}
return $services;
}
I try to print the matches it will give the result as
Array ( [0] => info1 [1] => 1 ) Array ( [0] => price_total1 [1] => 1 )
Array ( [0] => info2 [1] => 2 ) Array ( [0] => price_total2 [1] => 2 )
Thanks in advance.
try this. shorted version and don't use preg_match
function getServices($serviceinfo) {
$services = array();
if (is_array($serviceinfo) && !empty($serviceinfo)) {
foreach ($serviceinfo as $key => $value) {
if(strpos($key, 'info') === 0){
$services['service_'.substr($key, 4)]['info']=$value;
}elseif (strpos($key, 'price_total') === 0){
$services['service_'.substr($key, 11)]['price_total']=$value;
}
}
}
return $services;
}
$data = array('info1'=>'test service','price_total1'=>10,'info2'=>'test servicing','price_total2'=>5);
$service = getServices($data);
print_r($service);

Creating a new Array from an existing Array (php)

Okay I'm quite experienced with C# but am very new with PHP so please bear with me.
I have an existing array that looks a bit like this
Array
(
[0] => Array
(
[author] => Gavin
[weighting] => 2743
)
[1] => Array
(
[author] => Bob
[weighting] => 2546
)
[2] => Array
(
[author] => Gavin
[weighting] => 2227
)
)
Now what I want to do is loop through that and end up with a new array that has 2 keys (Gavin and Bob) and Bob's value is 2546 while Gavin's is 4970.
Right now I have this which nearly works but the last author gets a duplicate value and I can't sort it?
if (array_key_exists($authorName, $Authors)) {
foreach ($Authors as $key_name => &$key_value) {
if ($key_name == $authorName)
{
$key_value = $key_value + $weight;
}
}
}
else {
$Authors[$authorName] = $weight;
}
What am I doing wrong here?
This should do the trick
$newarray = array();
foreach($yourarray as $a) {
//create array if not created
if(!isset($newarray[$a['author']])) {
$newarray[$a['author']] = 0;
}
//put value in array
$newarray[$a['author']] += $a['weighting'];
}
$Authors = array();
foreach($array as $entry) {
if ( array_key_exists($entry['author'], $Authors) ) {
$Authors[ $entry['author'] ] += $entry['weighting'];
} else {
$Authors[ $entry['author'] ] = $entry['weighting'];
}
}
See it here in action: http://codepad.viper-7.com/LUx1r5

count of duplicate elements in an array in php

Hi,
How can we find the count of duplicate elements in a multidimensional array ?
I have an array like this
Array
(
[0] => Array
(
[lid] => 192
[lname] => sdsss
)
[1] => Array
(
[lid] => 202
[lname] => testing
)
[2] => Array
(
[lid] => 192
[lname] => sdsss
)
[3] => Array
(
[lid] => 202
[lname] => testing
)
)
How to find the count of each elements ?
i.e, count of entries with id 192,202 etc
You can adopt this trick; map each item of the array (which is an array itself) to its respective ['lid'] member and then use array_count_value() to do the counting for you.
array_count_values(array_map(function($item) {
return $item['lid'];
}, $arr);
Plus, it's a one-liner, thus adding to elite hacker status.
Update
Since 5.5 you can shorten it to:
array_count_values(array_column($arr, 'lid'));
foreach ($array as $value)
{
$numbers[$value[lid]]++;
}
foreach ($numbers as $key => $value)
{
echo 'numbers of '.$key.' equal '.$value.'<br/>';
}
Following code will count duplicate element of an array.Please review it and try this code
$arrayChars=array("green","red","yellow","green","red","yellow","green");
$arrLength=count($arrayChars);
$elementCount=array();
for($i=0;$i<$arrLength-1;$i++)
{
$key=$arrayChars[$i];
if($elementCount[$key]>=1)
{
$elementCount[$key]++;
} else {
$elementCount[$key]=1;
}
}
echo "<pre>";
print_r($elementCount);
OUTPUT:
Array
(
[green] => 3
[red] => 2
[yellow] => 2
)
You can also view similar questions with array handling on following link
http://solvemyquest.com/count-duplicant-element-array-php-without-using-built-function/
The following code will get the counts for all of them - anything > 1 at the end will be repeated.
<?php
$lidCount = array();
$lnameCount = array();
foreach ($yourArray as $arr) {
if (isset($lidCount[$arr['lid']])) {
$lidCount[$arr['lid']]++;
} else {
$lidCount[$arr['lid']] = 1;
}
if (isset($lnameCount [$arr['lname']])) {
$lnameCount [$arr['lname']]++;
} else {
$lnameCount [$arr['lname']] = 1;
}
}
$array = array('192', '202', '192', '202');
print_r(array_count_values($array));
$orders = array(
array(
'lid' => '',
'lname' => '',
))....
$foundIds = array();
foreach ( $orders as $index => $order )
{
if ( isset( $foundIds[$order['lid']] ) )
{
$orders[$index]['is_dupe'] = true;
$orders[$foundIds[$order['lid']]]['is_dupe'] = true;
} else {
$orders[$index]['is_dupe'] = false;
}
$foundIds[$order['lid']] = $index;
}
Try this code :
$array_count = array();
foreach ($array as $arr) :
if (in_array($arr, $array_count)) {
foreach ($array_count as $key => $count) :
if ($key == $arr) {
$array_count[$key]++;
break;
}
endforeach;
} else {
$array_count[$arr] = 1;
}
endforeach;
Check with in_array() function.

Looping an array through a second array

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.

Categories