create multi array php with two arrays - php

I have two arrays same like when var_dump:
$arr1 = array (size=2)
0 => string '10:2'
1 => string '10:1'
$arr2 = array (size=2)
0 => string '[{username:userA,email:userA#gmail.com'
1 => string 'username:userB,email:userB#gmail.com}]'
Now, i want to result same below:
$result = array (size=2)
'10:2' =>
array (size=2)
'username' => string 'userA'
'email' => string 'userA#gmail.com'
'10:1' =>
array (size=2)
'username' => string 'userB'
'email' => string 'userB#gmail.com'
Thanks for help!

I think this should do it:
// Turn string "key1:val1,key2,val2,..." into associative array.
function str_to_assoc($str) {
$str = str_replace(array('[{', '}]'), '', $str); // Remove extranous garbage
$arr = explode(',', $str);
$res = array();
foreach ($arr as $keyvalue) {
list($key, $value) = explode(':', $keyvalue);
$res[$key] = $value;
}
return $res;
$result = array_combine($arr1, array_map('str_to_assoc', $arr2));
It looks like $arr2 came from improperly parsing JSON by hand (maybe using preg_split()?). If you do:
$arr2 = json_decode($json_string);
then you should be able to get your result with just:
$result = array_combine($arr1, $arr2);

Related

extract only duplicate value from multidimensional array in php

I have array like this
$non_unique_zip
[0]->[0]91390
[1]ca
[2]1
[1]->[0]91391
[1]ca
[2]1
[2]->[0]91392
[1]ca
[2]1
[3]->[0]91390
[1]ca
[2]2
[4]->[0]91394
[1]ca
[2]2
so basically array has elements where arra[n][0] is zipcode and array[n][2] is buyer_id.
now out of this, i just want the zipcodes which have multiple buyers. so the only thing I want to extract is
[0]->[0]91390
[1]ca
since 91390 is the only zipcode which has buyer as 1 and 2.
I tried
$result = array();
$first = $non_unique_zip[0];
for($i=0; $i<count($non_unique_zip); $i++){
$result = array_intersect ($first, $non_unique_zip[$i]);
$first = $result;
}
but it just gives error undefined offset.
Any help will be appreciated.
If you call $records your starting array, here is a way to get the zips with 3 lines of code:
//array whose keys are zips, and values are # of occurances
$zips = array_count_values(array_column($records,0));
//filter keeps only zips which occur more than once.
$zips = array_filter($zips,function($n){return $n>1;});
//if you only need the zips, you're done! they are the keys
$zips = array_keys($zips);
Live demo
Use an array that keeps track of the zip codes that have already been encountered before. Then when you get a zip that's in that array, you know it's a duplicate.
$zips = array();
$result = array();
foreach ($non_unique_zip as $e) {
$code = $e[0];
if (isset($zips[$code])) { // duplicate, so add to $result
$result[$code] = array($code, $e[1]);
} else {
$zips[$code] = true; // first time, add it to $zips
}
}
Use array_walk like so:
<?php
$non_unique_zip = [
[91390, "ca"],
[91391, "ca"],
[91392, "ca"],
[91390, "ca"],
[91394, "ca"],
];
$unique_zip = [];
$duplicates = [];
array_walk($non_unique_zip, function($data) use(&$unique_zip, &$duplicates){
if(!in_array($data, $unique_zip)){
$unique_zip[] = $data;
}else{
$duplicates[] = $data;
}
});
var_dump( $duplicates );
// PRODUCES::
array (size=1)
0 =>
array (size=2)
0 => int 91390
1 => string 'ca' (length=2)
var_dump( $unique_zip );
// PRODUCES::
array (size=4)
0 =>
array (size=2)
0 => int 91390
1 => string 'ca' (length=2)
1 =>
array (size=2)
0 => int 91391
1 => string 'ca' (length=2)
2 =>
array (size=2)
0 => int 91392
1 => string 'ca' (length=2)
3 =>
array (size=2)
0 => int 91394
1 => string 'ca' (length=2)

Foreach loop always add first character of string to the array

I am making a function that can help me to cast the string to array, but that strange when the function always add first character to the array. Thank at first and this is code i used in function:
$string = '0:009987;1:12312;2:45231;3:00985;3:10923;4:11253;4:62341;4:01102;4:58710;4:10102;4:87093;4:12034;5:9801;6:1092;6:4305;6:1090;7:450;8:34';
$explodedString = explode(';', $string);
//var_dump($explodedString);
$takeArray = array();
$counti = 0;
foreach($explodedString as $exploded){
$secondExp = explode(':', $exploded);
var_dump($secondExp);
if(isset($takeArray[$secondExp[0]])){
$takeArray[$secondExp[0]][$counti] = $secondExp[1];
}else{
$takeArray[$secondExp[0]] = $secondExp[1];
}
$counti++;
}
var_dump($takeArray);
This is current output of this code:
array (size=9)
0 => string '009987' (length=6)
1 => string '12312' (length=5)
2 => string '45231' (length=5)
3 => string '00981' (length=5)
4 => string '11253 605181' (length=12)
5 => string '9801' (length=4)
6 => string '1092 41' (length=16)
7 => string '450' (length=3)
8 => string '34' (length=2)
Looking into row 4 you will see the string: '605181', this string come from the first character of each value belong to 4. But i need an output array like this:
[0] => {'009987'},
....
[4] => { '11253', '62341', ...., },
....
Please help me.
I'm not sure why you need $counti. All you need to do is, initialize the $takeArray[$n] if it doesn't exists, and push a new value to it. Something like this:
if(!isset($takeArray[$secondExp[0]])) {
// Initialize the array
$takeArray[$secondExp[0]] = array();
}
// Push the new value to the array
$takeArray[$secondExp[0]][] = $secondExp[1];
You only need to do the following :
$takeArray = array();
foreach($explodedString as $exploded) {
$secondExp = explode(':', $exploded);
$takeArray[(int)$secondExp[0]][] = $secondExp[1];
}
$string = '0:009987;1:12312;2:45231;3:00985;3:10923;4:11253;4:62341;4:01102;4:58710;4:10102;4:87093;4:12034;5:9801;6:1092;6:4305;6:1090;7:450;8:34';
$explodedString = explode(';', $string);
$takeArray = array();
foreach($explodedString as $exploded)
{
$secondExp = explode(':', $exploded);
$takeArray[$secondExp[0]][] = $secondExp[1];
}
var_dump($takeArray);

What do I need for doing this regex or split?

I have strings like the following that I have to split:
Other,CODSITE,Items::getCodCdeCli+Address::getNameAddress
Other,CODSITE,Items::getCodCdeCli
Items::getCode+Address::getName,CODSITE+Items::getSample,Items::getItemID
Other, CODSITE, CODSITE2
Into:
array(
array(
0 => 'Other',
1 => 'CODSITE',
2 => array(
'Items' => 'getCodCdeCli',
'Address' => 'getNameAddress'
)
),
//...
)
Each comma involve new information, if we have a '+' we need to append both data. If we have '::' we need to get first part as key of the result information.
For beginning this solution I have tried to split this on comma:
$re = "/([^,]+)/";
$str = "Other,CODSITE,Items::getCodCdeCli+Address::getNameAddress";
preg_match_all($re, $str, $matches);
for now with this regex I have this:
array (size=2)
0 =>
array (size=3)
0 => string 'Other' (length=5)
1 => string 'CODSITE' (length=7)
2 => string 'Items::getCodCdeCli+Address::getNameAddress' (length=43)
1 =>
array (size=3)
0 => string 'Other' (length=5)
1 => string 'CODSITE' (length=7)
2 => string 'Items::getCodCdeCli+Address::getNameAddress' (length=43)
Which is wrong. I have same result twice.. and line 2 => [...] is not split (which is normal with my regex)
One way of doing it in single pass is by using array_combine function like this:
$str = 'Other,CODSITE,Items::getCodCdeCli+Address::getNameAddress';
if ( preg_match_all('~(?|[,+]([^,+]+)::([^,+]+)|([^,]+))~', $str, $m) )
print_r( array_combine ( $m[1], $m[2] ) );
Output:
Array
(
[Other] =>
[CODSITE] =>
[Items] => getCodCdeCli
[Address] => getNameAddress
)
Does it need to be regex? It might be possible to achieve this with a couple of explodes and foreach loops:
$str = 'Other,CODSITE,Items::getCodCdeCli+Address::getNameAddress';
//new entry per comma (,)
$results = explode(',',$str);
//check each entry for array information
foreach($results as &$result) {
if(strpos($result,'+') !== FALSE) {
//explode array information
$bits1 = explode('+',$result);
$result = array();
foreach($bits1 as &$subresult) {
//format array information into key => value pairs
if(strpos($subresult,'::') !== FALSE) {
$bits = explode('::',$subresult);
$result[$bits[0]] = $bits[1];
}
}
}
}
var_dump($results);
/**
* array (size=3)
* 0 => string 'Other' (length=5)
* 1 => string 'CODSITE' (length=7)
* 2 => array (size=2)
* 'Items' => string 'getCodCdeCli' (length=12)
* 'Address' => string 'getNameAddress' (length=14)
*/
With the help of #Richard Parnaby-King answer. This is the solution, in fact no regex is needed even if i'm sure we can use it for the same result.
$lines = array(
0 => 'Other,CODSITE,Items::getCodCdeCli+Address::getNameAddress',
2 => 'Other,CODSITE,Items::getCodCdeCli',
3 => 'Items::getCode+Address::getName,CODSITE+Items::getSample,Items::getItemID',
4 => 'Other, CODSITE, CODSITE2',
);
foreach ($lines as $input) {
$informations = explode(',', $input);
$result = array();
foreach ($informations as $information) {
if(strpos($information, '+') !== FALSE) {
$classes = explode('+',$information);
$temp = array();
foreach($classes as $subresult) {
if(strpos($subresult,'::') !== FALSE) {
$classAndMethod = explode('::',$subresult);
$temp[$classAndMethod[0]] = $classAndMethod[1];
} else {
$temp[] = trim($subresult);
}
}
$result[] = $temp;
} elseif (strpos($information, '::') !== FALSE) {
$classAndMethod = explode('::',$information);
$result[][$classAndMethod[0]] = $classAndMethod[1];
} else {
$result[] = trim($information);
}
}
var_dump($result);
}
It works !

alternative to eval('$array_test = array('.$test.');')

I'm looking for an alternative to
$test = "1=>'msg_test1',3=>'msg_test2',9=>'msg_test3'";
eval('$array_test = array('.$test.');');
does anyone have an idea how i can make it to have an array in a secure way from a string?
Thanks in advance for your help!
You could parse it manually with explode() like so:
$test = "1=>'msg_test1,3=>'msg_test2,9=>'msg_test3'";
$array_test = array();
foreach(explode(',', substr($test, 0, -1)) as $row)
{
$split = explode('=>\'', $row);
$array_test[$split[0]] = $split[1];
}
var_dump($array_test);
Produces:
array (size=3)
1 => string 'msg_test1' (length=9)
3 => string 'msg_test2' (length=9)
9 => string 'msg_test3' (length=9)
If I understand your question then you cshould format your string like this
$test = "value1,value2,value2";
Then proceed with and explode
$array_test = explode(',', $test);
your array
$array_test = array(
'1' => 'value1'
'2' => 'value2'
'3' => 'value3'
);

How to save json_decoded values (only) as one string into a $var

Im receiving the following variable sent as a json array from javascript: $_REQUEST['fb_friend_uid']
I then decode the array and then do a var_dump
$string = json_encode($_REQUEST['fb_friend_uid']);
$result = json_decode($string, true);
var_dump($result);
The var_dump shows me the following
array (size=360)
0 =>
array (size=1)
'id' => string '263901486' (length=9)
1 =>
array (size=1)
'id' => string '502533736' (length=9)
2 =>
array (size=1)
'id' => string '506526230' (length=9)
3 =>
array (size=1)
'id' => string '507245473' (length=9)
etc..
How would I go about saving all values from 'id' into one new $var_string ? - formatted like: "263901486, 502533736, 506526230"
Objective is to use the string in an sql query like so:
SELECT * FROM vote WHERE
vote_fb_uid IN ($var_string)
Try this :
$string = json_encode($_REQUEST['fb_friend_uid']);
$result = json_decode($string, true);
$res_array = array();
foreach($result as $val){
$res_array[] = $val['id'];
}
$res_string = implode(",",$res_array);
If you want all the items to be combined to one long string you can try imploding the array
http://php.net/manual/en/function.implode.php
$varString = implode(',', $_REQUEST['fb_friend_uid'])
I don't really know PHP, but looking at the docs, you should be able to write something along the lines of:
$string = json_encode($_REQUEST['fb_friend_uid']);
$result = json_decode($string, true);
$res_array = array_map(function ($val) { return $val['id']; });
$res_string = join(",", $res_array);
(Adapted from Prasanth Bendra's answer.)
Try this
$string = json_encode($ar);
$result = json_decode($string, true);
$res_array = array();
foreach($result as $val){
$res_array[] = $val['id'];
}
$res_string = "'".implode("','", $res_array)."'";
$qry = "SELECT * FROM vote WHERE vote_fb_uid IN ($res_string)";

Categories