Optimize the creation of sub arrays based on string prefix - php

In my last question, was created a way to divide a array based in the string pattern Father_son, but now i need a way to split too a new pattern: Father_N_son
Original (generated by http://ideone.com/pmHHR code) :
array
'Pagamento' =>
array
'data' => string '' (length=0)
'0_pessoaId' => string '85' (length=2)
'0_valorBruto' => string '890.00' (length=6)
'1_pessoaId' => string '83' (length=2)
'1_valorBruto' => string '20.00' (length=5)
Now i need:
array
'Pagamento' =>
array
'data' => string '' (length=0)
0 =>
array
'pessoaId' => string '85' (length=2)
'valorBruto' => string '890.00' (length=6)
1 =>
array
'pessoaId' => string '83' (length=2)
'valorBruto' => string '20.00' (length=5)
Thanks,
Celso

my solution with regex:
static function parserRequest($array = null) {
if (empty($array)) {
$array = $_REQUEST;
}
foreach ($array as $k => $v) {
$name = explode('_', $k);
$newkey = array_shift($name);
$newname = implode('_', $name);
//para o padrão Entidade.n.atributo
if(preg_match("/[0-9]_[a-z]/", strtolower($newname))){
$nameValued = explode('_',$newname);
$newkeyValued = array_shift($name);
$newnameValue = implode('_', $name);
$result[$newkey][$newkeyValued][$newnameValue] = $v;
}else{
//para o padrão Entidade.atributo
$result[$newkey][$newname] = $v;
}
}
return $result;
}

Related

Merge inner PHP arrays into one multidimensional array - No duplicates basing on Key value

I have tried a number of PHP functions like array_unique to merge the arrays I have but that does not work since these are not strings.
The starting output would be this on var_dump( $country_cities );
array (size=3)
0 =>
array (size=1)
'BH' =>
array (size=4)
'post_id' => int 7886
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Laurence' (length=8)
'city_name_arabic' => string '3684hdfpfwbhisf' (length=15)
1 =>
array (size=1)
'BH' =>
array (size=4)
'post_id' => int 7885
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Bahrain City' (length=12)
'city_name_arabic' => string 'vgdg824762' (length=10)
2 =>
array (size=2)
'BH' =>
array (size=4)
'post_id' => int 7885
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Bahrain City' (length=12)
'city_name_arabic' => string 'vgdg824762' (length=10)
'KW' =>
array (size=4)
'post_id' => int 7841
'country' => string 'KW' (length=2)
'city_name_eng' => string 'Kuwait City' (length=11)
'city_name_arabic' => string ' مدينة الكويت' (length=24)
The Code below merges the different arrays above.
<?php
// Make the cities unique. Remove duplicates form the inner array.
$uniques = [];
foreach($country_cities as $arr ) {
foreach( $arr as $v) {
if( !in_array($v, $uniques, false) ) {
$uniques[$v['country']] = $v;
}
}
}
var_dump($uniques);
Results logged show the code cuts out some of the arrays.
/Users/..... on line php:74:
array (size=2)
'BH' =>
array (size=4)
'post_id' => int 7885
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Bahrain City' (length=12)
'city_name_arabic' => string 'vgdg824762' (length=10)
'KW' =>
array (size=4)
'post_id' => int 7841
'country' => string 'KW' (length=2)
'city_name_eng' => string 'Kuwait City' (length=11)
'city_name_arabic' => string ' مدينة الكويت' (length=24)
Please help figure out my error or suggest a better way to fix it.
If I understood you correctly, this should be the result you wanted to achieve.
Each country code will be included once, while the cities (based on post_id) will only be added once.
<?php
$result = [];
$processedIds = [];
foreach ($country_cities as $ccs) {
foreach ($ccs as $cc => $details) {
// If the country has not yet been added to
// the result we create an outer array.
if (!key_exists($cc, $result)) {
$result[$cc] = [];
}
$postId = $details['post_id'];
if (!in_array($postId, $processedIds)) {
// Add the unique city to country's collection
$result[$cc][] = $details;
// Keep track of the post_id key.
$processedIds[] = $postId;
}
}
}
print_r($result);
<?php
//...
$uniques = [];
foreach($country_cities as $data ) {
foreach( $data as $countryCode => $item) {
if( !array_key_exists($countryCode, $uniques) ) {
$uniques[$countryCode] = []; //Create an empty array
}
$targetArray = &$uniques[$countryCode];
if( !array_key_exists($item['post_id'], $targetArray) ) {
$targetArray[$item['post_id']] = $item; //Create an empty array
}
}
}
Maybe this code will help?

Merging array values into single key and multiple values in php

I want the array to merge into a key value pair. look at the example below
Here is my code and array $aExtraFilter
array (size=4)
0 =>
array (size=2)
'key' => string 'CookTech' (length=8)
'value' => string 'Broil' (length=5)
1 =>
array (size=2)
'key' => string 'CookTech' (length=8)
'value' => string 'Pan Fry' (length=7)
2 =>
array (size=2)
'key' => string 'CookSkills' (length=10)
'value' => string 'Intro' (length=5)
3 =>
array (size=2)
'key' => string 'CookSkills' (length=10)
'value' => string 'Knife Skills' (length=12)
Here is my code:
$aExtraFilter2 = [];
$extrafilterkey = '';
$extrafiltervalue = [];
foreach ($aExtraFilter as $key => $value) {
$extrafilterkey = $value['key'];
$aExtraFilter2[$extrafilterkey] = [];
array_push($extrafiltervalue, $value['value']);
$aExtraFilter2[$extrafilterkey] = implode(',', $extrafiltervalue);
}
var_dump($aExtraFilter2);
the output is :
array (size=2)
'CookTech' => string 'Broil,Pan Fry' (length=13)
'CookSkills' => string 'Broil,Pan Fry,Intro,Knife Skills' (length=32)
I want it to look like this:
array (size=2)
'CookTech' => string 'Broil,Pan Fry' (length=13)
'CookSkills' => string 'Intro,Knife Skills' (length=32)
I think I'm almost there but I guess I need some help.
This line does nothing because it is superseded just a bit later as the same variable is being set:
$aExtraFilter2[$extrafilterkey] = [];
This line appends to the array regardless of what you have as $value['key'], which is why you get all keys lumped together in the output:
array_push($extrafiltervalue, $value['value']);
This will produce a desired output:
// fill array of arrays
$aExtraFilter2 = [];
foreach ($aExtraFilter as $key => $value) {
if (!array_key_exists($value['key'], $aExtraFilter2)) $aExtraFilter2[$value['key']] = [];
$aExtraFilter2[$value['key']][] = $value['value'];
}
// convert to string (if needed at all, depends on what you're doing later)
foreach ($aExtraFilter2 as $key => $set) {
$aExtraFilter2[$key] = join(',', $set);
}
The typical way to code this is by creating a temporary structure, based on the key and comprising an array with the values:
$tmp = [];
foreach ($aExtraFilter as $pair) {
$tmp[$pair['key']][] = $pair['value'];
}
The structure would look like this afterwards:
[
'CookTech' => ['Broil', 'Pan Fry'],
'CookSkills' => ['Intro', 'Knife Skills'],
]
Then, you map that array against the representation you want to have:
$aExtraFilter2 = array_map(function($values) {
return join(',', $values);
}, $tmp);
See also: array_map()

PHP Array Create from given Array

Thsi is my array structure.
$arr = array(
'Tablet'=>array('test1','test2'),
'Medicine'=>array('abc1'.'abc2'),
'Dosage'=>array('1','1'),
'Mode'=>array('testmode1','testmodel2'),
'Since'=>array('mng','mng')
);
I want to create an array like this.
array
0 =>
array
'Tablet' => string 'test1' (length=5)
'Medicine' => string 'abc1' (length=4)
'Dosage' => string '1' (length=1)
'Mode' => string 'testmode1' (length=9)
'Since' => string 'mng' (length=3)
1 =>
array
'Tablet' => string 'test2' (length=5)
'Medicine' => string 'abc1' (length=4)
'Dosage' => string '1' (length=1)
'Mode' => string 'testmode2' (length=9)
'Since' => string 'mng' (length=3)
Can someone pls help?
Sorry for bad english.
Thanks
$new = [];
foreach ($arr as $key => $sub) {
$i = 0;
foreach ($sub as $value) {
$new[$i][$key] = $value;
$i++;
}
}
That should do the trick :)
$newArr = array();
foreach ( $arr as $key => $subArr ){
for ($i= 0; $i < count($subArr); $i++){
if (!array_key_exists($i, $newArr)){
$newArr[$i] = array();
}
$newArr[$i][$key] = $subArr[$i];
}
}
$arr = array(
'Tablet'=>array('test1','test2'),
'Medicine'=>array('abc1','abc2'),
'Dosage'=>array('1','1'),
'Mode'=>array('testmode1','testmodel2'),
'Since'=>array('mng','mng')
);
$na=array();
foreach($arr as $k=>$v){
foreach($v as $kk=>$vv){
$na[$kk][$k]=$vv;
}
}
echo "<pre>";print_r($na);
Easy you can append each one to normal array like this
$arr1 = array(
'Tablet'=>array('test1','test2'),
'Medicine'=>array('abc1'.'abc2'),
'Dosage'=>array('1','1'),
'Mode'=>array('testmode1','testmodel2'),
'Since'=>array('mng','mng')
);
$arr2 = array(
'Tablet'=>array('test1','test2'),
'Medicine'=>array('abc1'.'abc2'),
'Dosage'=>array('1','1'),
'Mode'=>array('testmode1','testmodel2'),
'Since'=>array('mng','mng')
);
$arr3 = array(
'Tablet'=>array('test1','test2'),
'Medicine'=>array('abc1'.'abc2'),
'Dosage'=>array('1','1'),
'Mode'=>array('testmode1','testmodel2'),
'Since'=>array('mng','mng')
);
$a=array();
array_push($a,arr1,arr2,arr3);
print_r($a);
output will look
array
0 =>
array
'Tablet' => string 'test1' (length=5)
'Medicine' => string 'abc1' (length=4)
'Dosage' => string '1' (length=1)
'Mode' => string 'testmode1' (length=9)
'Since' => string 'mng' (length=3)
1 =>
array
'Tablet' => string 'test2' (length=5)
'Medicine' => string 'abc1' (length=4)
'Dosage' => string '1' (length=1)
'Mode' => string 'testmode2' (length=9)
'Since' => string 'mng' (length=3)
$myLength = count($arr['Tablet'])
$newArray = array();
for (i=0; i < $myLength ; i++)
{
$newArray[i]['Tablet'] = $arr['Tablet'][i];
$newArray[i]['Medicine'] = $arr['Medicine'][i];
$newArray[i]['Dosage'] = $arr['Dosage'][i];
$newArray[i]['Mode'] = $arr['Mode'][i];
$newArray[i]['Since'] = $arr['Since'][i];
}
What do you meant adding the (lentgh = x) in your question?

How to convert stdClass object in to refrence array? (PHP)

I have variable $related witch is stdCalss object and i want to convert it with one foreach loop in to reffrence array.
Var_dump of Object $related:
array (size=19)
0 =>
object(stdClass)[20]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1567' (length=4)
1 =>
object(stdClass)[21]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1562' (length=4)
2 =>
object(stdClass)[22]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1564' (length=4)
3 =>
object(stdClass)[23]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1410' (length=4)
4 =>
object(stdClass)[24]
public 'id_product' => string '111' (length=3)
public 'related' => string '77' (length=2)
5 =>
object(stdClass)[25]
public 'id_product' => string '111' (length=3)
public 'related' => string '1610' (length=4)
Php code:
foreach ($related AS $r){
????
}
var_dump($rels);
Wished Output:
$rels = array(
'1568'=>'1567, 1562, 1564, 1410',
'111'=>'77,1610'
);
Build a temporary array and implode it:
foreach($related AS $r) {
$temp[$r->id_product][] = $r->related;
$rels[$r->id_product] = implode(', ', $temp[$r->id_product]);
}
print_r($rels);
$rels = array ();
foreach ($related as $r){
$rels[$r->id_product] .= $r->related . ","; // put all of them with respective key together
}
$rels = array_map(
function ($a) {
$a = preg_replace('~,(?!.*,)~', '', $a);
return $a;
}
,$rels); // remove last commas
var_dump($rels);
Try,
$rels = array();
foreach($related as $r){
$rels[$r->id_product] .= $r->related.', ';
}
array_walk_recursive($related, function(&$item){
$item = rtrim($item,', ');
});
From the PHP docs: http://php.net/manual/en/language.types.type-juggling.php

Unique PHP Array

How can I check if the values are unique in an array based on the key value? Below is the out put of the array. I want to remove duplicate values based on the "id" key. If you check below, the 2nd & 3rd array are same except for the "role" value. Because of this, array_unique is not working on this array.
array
0 =>
array
'id' => string '1521422' (length=7)
'name' => string 'David Alvarado' (length=14)
'role' => string 'associate producer ' (length=20)
1 =>
array
'id' => string '0098210' (length=7)
'name' => string 'Cristian Bostanescu' (length=19)
'role' => string 'line producer: Romania (as Cristi Bostanescu)' (length=46)
2 =>
array
'id' => string '1266015' (length=7)
'name' => string 'Bruno Hoefler' (length=13)
'role' => string 'co-producer ' (length=13)
3 =>
array
'id' => string '1266015' (length=7)
'name' => string 'Bruno Hoefler' (length=13)
'role' => string 'executive producer ' (length=20)
4 =>
array
'id' => string '1672379' (length=7)
'name' => string 'Alwyn Kushner' (length=13)
'role' => string 'associate producer ' (length=20)
Try this one:
<?php
$array = array(
array('id' => 1, 'text' => 'a'),
array('id' => 2, 'text' => 'b'),
array('id' => 1, 'text' => 'c'),
array('id' => 3, 'text' => 'd')
);
$array = array_filter($array, function ($item) {
static $found = array();
if (isset($found[$item['id']])) return false;
$found[$item['id']] = true;
return true;
});
var_dump($array);
This works as of PHP 5.3 (because of the closure and static statement).
cf. http://php.net/manual/en/function.array-filter.php for more information. I tested the statement within loops, it works there as well.
Basically you want to implement a variation of array_unique that does what you want:
function array_unique_multi($arr,$key='id') {
// $arr is the array to work on
// $key is the key to make unique by
$ret = Array();
foreach($arr as $v) {
if( !isset($ret[$v[$key]])) $ret[$v[$key]] = $k;
}
return array_values($ret);
}
You can use this code:
// assuming $arr is your original array
$narr = array();
foreach($arr as $key => $value) {
//$narr[json_encode($value)] = $key;
if (!array_key_exists($value["id"], $narr))
$narr[$value["id"]] = $key;
}
$narr = array_flip($narr);
foreach($arr as $key => $value) {
if (!array_key_exists($key, $narr))
unset($arr[$key]);
}
print_r($arr); // will have no duplicates

Categories