how to split a string and build an associative array php? - php

How to split a string in PHP ? For example, if i have the string like
Array([0] => "1=>10,2=>9,3=>7,1=>9,2=>8,3=>7");
how can i get
Array([0] => 1=>10,2=>9,3=>7 [1] => 1=>9,2=>8,3=>7);
and later i want to build an associative array like for example,
$ratings = array(6533 => ['Build Quality' => [1=>10,2=>9,3=>7],
'Versatility' => [1=>9,2=>8,3=>7],
'value' => [1=>9.5,2=>7,3=>6]]);
//takes the current post id and returns an product ratings array
function get_ratings($current_post_id){
$product_post = get_post($current_post_id);
preg_match_all("/\[v360_product_table\s.*?\]/", $product_post>post_content, $product_elements);
$product_elements = $product_elements[0][0];
preg_match_all('/"([^"]+)"/', $product_elements, $parameters);
$product_params = $parameters[0][0];
$rating_params = preg_split('","', $product_params);
$rating_factors = str_replace('"', '', $rating_params);
$b = print_r($rating_factors);
/* output: Array ( [0] => Build Quality [1] => Versatality [2] => Adoptability) */
$product_rank = $parameters[0][1];
/* output: Array ( [0] => 1=>10,2=>9,3=>7,1=>9,2=>8,3=>7 ) */
$rank_split = preg_split('"**have to split it here**"', $product_rank);
$rank_values = str_replace('"', '', $rank_split);
$assoc_array = array_combine($rating_factors, $rank_values);
/* needs to construct an array like '$ratings' */
$ratings = array(6533 => ['Build Quality' => [1 => 10, 2 => 8, 3 => 7],
'Versatility' => [1 => 9, 2 => 9, 3 => 8], 'Value' => [1 => 10, 2 => 8,3 => 8]]);
return $ratings[$current_post_id];
}

From your examples, I'm guessing you want to split the string by commas followed by the number 1. To do this, you can use preg_split() with a positive lookahead:
$string = "1=>10,2=>9,3=>7,1=>9,2=>8,3=>7";
$split = preg_split('/,(?=1\b)/', $string);
var_dump($split);
Gives:
array(2) {
[0]=>
string(15) "1=>10,2=>9,3=>7"
[1]=>
string(14) "1=>9,2=>8,3=>7"
}
This function will parse out the whole string into a nested array:
function split_string($string)
{
$split = array();
foreach (preg_split('/,(?=1\b)/', $string) as $row => $part1) {
foreach (explode(',', $part1) as $part2) {
list($key, $value) = explode('=>', $part2, 2);
$split[$row][$key] = $value;
}
}
return $split;
}
Tested as follows (in php 5.6):
$string = "1=>10,2=>9,3=>7,1=>9,2=>8,3=>7";
$split = split_string($string);
var_dump($split);
Gives this output:
array(2) {
[0]=>
array(3) {
[1]=>
string(2) "10"
[2]=>
string(1) "9"
[3]=>
string(1) "7"
}
[1]=>
array(3) {
[1]=>
string(1) "9"
[2]=>
string(1) "8"
[3]=>
string(1) "7"
}
}
You could then use array_combine() for example to merge in the names:
$string = "1=>10,2=>9,3=>7,1=>9,2=>8,3=>7";
$split = split_string($string);
var_dump(array_combine(array('Build Quality', 'Versatility'), $split));

Related

PHP add counter to name if already exists in array

I have the following multi-dimensional array and I need to iterate over it and wherever there is a duplicate name, a counter is added to the name.
[1] => Array
(
[0] => Array
(
[clientName] => John Smith
[clientType] => 0
[clientDOB] => 1980-10-14
)
)
[2] => Array
(
[0] => Array
(
[clientName] => John Smith
[clientType] => 0
[clientDOB] => 1970-01-01
)
[1] => Array
(
[clientName] => Jeremy White
[clientType] => 2
[clientDOB] => 2015-08-19
)
)
The code I'm using is this :
$finalNames = array_map(function ($item) use (&$namesCount) {
if (!isset($namesCount[$item['clientName']])) {
$namesCount[$item['clientName']] = 0;
}
$namesCount[$item['clientName']]++;
$item['clientName'] = $item['clientName'] . ' ' . $namesCount[$item['clientName']];
return $item;
}, $arrayOfTravellers);
array_map(function($item, $key) use ($namesCount, &$finalNames) {
$finalNames[$key]['clientName'] = $namesCount[$item['clientName']] == 1
? str_replace(' 1', '', $finalNames[$key]['clientName'])
: $finalNames[$key]['clientName'];
}, $arrayOfNames, array_keys($arrayOfTravellers));
Which is returning a bunch of errors such as :
Notice: Undefined index: clientName in /Applications/MAMP/htdocs/europatours/functions/reportsFunctions.php on line 330
My assumption is that the code is not fit for a multi-dimensional array. Can anyone help please? I need to retain the complete structure of the array only where there is a duplicate name, a counter is added such as John Smith 1, John Smith 2 whereas Jeremy White remains without a counter.
$arrayOfNames = array(
array('clientName' => 'John'),
array('clientName' => 'John'),
array('clientName' => 'Mary'),
array('clientName' => 'Mary'),
array('clientName' => 'Mary'),
array('clientName' => 'Tony'),
array('clientName' => 'Alex')
);
$namesCount = array();
$finalNames = array_map(function ($item) use (&$namesCount) {
if (!isset($namesCount[$item['clientName']])) {
$namesCount[$item['clientName']] = 0;
}
$namesCount[$item['clientName']]++;
$item['clientName'] = $item['clientName'] . ' ' . $namesCount[$item['clientName']];
return $item;
}, $arrayOfNames);
array_map(function($item, $key) use ($namesCount, &$finalNames) {
$finalNames[$key]['clientName'] = $namesCount[$item['clientName']] == 1
? str_replace(' 1', '', $finalNames[$key]['clientName'])
: $finalNames[$key]['clientName'];
}, $arrayOfNames, array_keys($arrayOfNames));
echo '<pre>';
var_dump($finalNames);
echo '</pre>';
The output would be:
array(7) {
[0]=>
array(1) {
["clientName"]=>
string(6) "John 1"
}
[1]=>
array(1) {
["clientName"]=>
string(6) "John 2"
}
[2]=>
array(1) {
["clientName"]=>
string(6) "Mary 1"
}
[3]=>
array(1) {
["clientName"]=>
string(6) "Mary 2"
}
[4]=>
array(1) {
["clientName"]=>
string(6) "Mary 3"
}
[5]=>
array(1) {
["clientName"]=>
string(4) "Tony"
}
[6]=>
array(1) {
["clientName"]=>
string(4) "Alex"
}
}
What about a combination of array_column and in_array when adding new values?
$records = array(); // your data
$name = 'John';
$i = 0;
do
{
$newName = $name . ( ($i == 0)? '' : ' '.$i );
$i++;
}
while (in_array($newName, array_column($records, 'clientName')));
$records[] = array('clientName' => $newName);
Due to performance issues you may want to call array_columns only once before the loop and store the results in a variable.

Sort array by the value of the key

i'm trying to sort an array by the value of a sub-key in DESC order but I'm stuck.
I've could make it with ksort but it was in ascending order..
Here's my array :
array_by_lang => array(
[no] => array(
[3-1] => array(//some informations),
[3-10] => array(//informations),
[3-7] => array(//informations),
[5-1] => array(//informations)
)
)
what i want to obtain is something like :
array_by_lang => array(
[no] => array(
[5-1] => array(//informations),
[3-10] => array(//some informations),
[3-7] => array(//informations),
[3-1] => array(//informations)
)
)
Is that possible ? Thanks a lot
I think, you need "reversing natural sort by key". Just with array_multisort and array_reverse (see also natsort):
$array_by_lang = array(
'no' => array(
'3-1' => array('info_1'),
'3-10' => array('info_2'),
'3-7' => array('info_3'),
'5-1' => array('info_4'),
)
);
array_multisort(array_keys($array_by_lang['no']),SORT_NATURAL, $array_by_lang['no']);
$array_by_lang['no'] = array_reverse($array_by_lang['no']); // reverse natural order - "DESC"
var_dump($array_by_lang);
Output
array(1) {
["no"]=>
array(4) {
["5-1"]=>
array(1) {
[0]=>
string(6) "info_4"
}
["3-10"]=>
array(1) {
[0]=>
string(6) "info_2"
}
["3-7"]=>
array(1) {
[0]=>
string(6) "info_3"
}
["3-1"]=>
array(1) {
[0]=>
string(6) "info_1"
}
}
}
This might help -
$a = array(
'3-1' => array('//some informations'),
'3-10' => array('//informations'),
'3-7' => array('//informations'),
'5-1' => array('//informations')
);
## Array for keys
$temp= array();
foreach(array_keys($a) as $v) {
$t = explode('-', $v);
$temp[$t[0]][] = $t[1];
}
## Sort the keys
foreach($temp as &$ar) {
rsort($ar);
}
krsort($temp);
## Final array
$final= array();
foreach($temp as $k => $f) {
foreach($f as $v) {
$key = $k . '-' . $v;
$final[$key] = $a[$key];
}
}
var_dump($final);
Output
array(4) {
["5-1"]=>
array(1) {
[0]=>
string(14) "//informations"
}
["3-10"]=>
array(1) {
[0]=>
string(14) "//informations"
}
["3-7"]=>
array(1) {
[0]=>
string(14) "//informations"
}
["3-1"]=>
array(1) {
[0]=>
string(19) "//some informations"
}
}
DEMO

Search values in php array

I have an array like this:
array(5) {
[0]=> array(1) { ["go-out"]=> string(7) "#0d4b77" }
[1]=> array(1) { ["cycling"]=> string(7) "#1472b7" }
[2]=> array(1) { ["diving"]=> string(7) "#1e73be" }
[3]=> array(1) { ["exploring"]=> string(7) "#062338" }
[4]=> array(1) { ["eating"]=> string(7) "#f79e1b" }
}
Let's say I have the first value like 'cycling', so how can I find the '#147217' value?
I have been trying a lot of combinations of
foreach ( $array as $key => list($key1 ,$val)) {
if ($key1 === $id) {
return $val;
}
}
But no luck.
Ideas?
You can use array_column -
array_column($your_array, 'cycling');
DEMO
You should also add the checks for key's existence.
you may still make one loop
$id = "cycling";
foreach($array as $val)
if(isset($val[$id])) echo $val[$id];
Demo on Evail.in
I have reformated tour code, try this, that works:
$array = array(
0 => array("go-out" => "#0d4b77"),
1 => array("cycling" => "#1472b7"),
2 => array("diving" => "#1e73be"),
3 => array("exploring" => "#062338"),
4 => array("eating" => "#f79e1b")
);
$id = "cycling";
foreach ($array as $key => $entry) {
if ($entry[$id]) {
echo $entry[$id];
}
}
$array = array(
0 => array("go-out" => "#0d4b77"),
1 => array("cycling" => "#1472b7"),
2 => array("diving" => "#1e73be"),
3 => array("exploring" => "#062338"),
4 => array("eating" => "#f79e1b")
);
$search = "cycling";
foreach ($array as $key => $entry)
if (isset($entry[$search]))
echo $entry[$search];
That works.
Nice day.

Reading PHP array using key value

I have an array that I'm creating inside my PHP script, the var_dump function gives me this value :var_dump($arrayOfValues);
array(3) {
[0]=> array(2) {
[0]=> string(12) "BusinessName"
[1]=> string(13) "ITCompany"
}
[1]=> array(2) {
[0]=> string(7) "Address"
[1]=> string(58) "29 xxxxxx,Canada"
}
[2]=> array(2) {
[0]=> string(20) "PrimaryBusinessPhone"
[1]=> string(14) "(444) 111-1111"
}
[3]=> array(2) {
[0]=> string(13) "BusinessEmail"
[1]=> string(24) "xx#example.com"
}
}
I would like to access to the value of the "BusinessName" using key and not index so if I put : echo $arrayOfValue[0][1]; it gives me the BusinessName that is ITCompany but if I put
: echo $arrayOfValue['BusinessName'][1]; it gives nothing so how can I fix that please?
The array is initialized $arrayOfValue = array(); and then populated dynamically inside a for loop like that
$arrayOfValue[] = array($Label, $Value);
your array has this kind of data
$arrayOfPostsValue[] = array("BusinessName","ITCompany");
$arrayOfPostsValue[] = array("Address","29 xxxxxx,Canada");
$arrayOfPostsValue[] = array("PrimaryBusinessPhone","(444) 111-1111");
$arrayOfPostsValue[] = array("BusinessEmail","xx#example.com");
there is no array key in data So, you have to recreate your desire array
$newArrayOfPostsValue = array();
foreach ( $arrayOfPostsValue as $value ){
$newArrayOfPostsValue[$value[0]] = $value[1];
}
print_r($newArrayOfPostsValue);
and here is output
Array
(
[BusinessName] => ITCompany
[Address] => 29 xxxxxx,Canada
[PrimaryBusinessPhone] => (444) 111-1111
[BusinessEmail] => xx#example.com
)
As mentioned in the comment, change the structure of the array, it will be much easier to handle
$my_array = array(
array('Business Name' => 'It Company'),
array('Address' => 'My address')
);
Looking at the content of your array, I will restructure it as
$my_improved_array = array(
'BusinessName' => 'It Company',
'Address' => 'My Address',
);
This is how you can access,
echo $my_array[0]['BusinessName'] //prints 'It Company'
echo $my_array[1]['Address'] //prints 'My Address'
echo $my_improved_array['BusinessName'] // prints 'It Company'
Try like this and save array as key value pairs and then access the key:
foreach($arrayOfValues as $a)
$arr[$a[0]] = $a[1];
echo $arr['BusinessName'];
While creating that array build it with index as BusinessName
array (
0 => array(
'BusinessName'=> "ITCompany"
)
1 => array(1) (
'Address'=> "29 xxxxxx,Canada"
)
)
etc..
PHP Array example
$array = array();
$array['BusinessName'] = 'ITCompany';
$array['Address'] = '29 xxxxxx,Canada';
And so on... Now you can echo values with
echo $array['BusinessName'];
Also this works
$array = array('BusinessName' => 'ITCompany', 'Address' => '29 xxxxxx,Canada');
First of all, how are you building this array ? Maybe you can directly make a workable array.
Anyway, you can do something like this :
$oldArray = Array(
Array("BusinessName", "ITCompany"),
Array("Address", "29 xxxxxx,Canada"),
Array("PrimaryBusinessPhone", "(444) 111-1111"),
Array("BusinessEmail", "xx#example.com")
);
$newArray = Array();
foreach($oldArray as value) {
$newValue[$value[0]] = $value[1];
}
/* Now, it's equal to
$newArray = Array(
"BusinessName" => "ITCompany",
"Address" => "29 xxxxxx,Canada",
"PrimaryBusinessPhone" => "(444) 111-1111",
"BusinessEmail" => "xx#example.com"
);
*/

Global array in php issues

I've found some very helpful answers but still have some problems.
I want to put different rows in global array, WITHOUT removing the other rows.
<?php
global $global_arr;
function first() {
///some code
global $global_arr;
$global_arr[] = array('first' =>
array('1' , '1', '1'));
}
function second() {
///some code
global $global_arr;
$global_arr[] = array('second' =>
array('2' , '2', '2'));
}
function third() {
///some code
global $global_arr;
$global_arr[] = array('third' =>
array('3' , '3', '3'));
}
first();
second();
third();
print_r($global_arr);
I want every of the functions to index the array and add rows respectevly
Thank you in advance!
Edit :
Thank to your help here is the working version :
function first($arr) {
$arr[] = array('first' =>
array(1, 1, 1));
return $arr;
}
function second($arr) {
$arr[] = array('second' =>
array(2, 2, 2));
return $arr;
}
$arr = array();
$arr = first($arr);
$arr = second($arr);
print_r($arr);
Output :
Array ( [0] => Array ( [first] => Array ( [0] => 1 [1] => 1 [2] => 1 ) ) [1] => Array ( [second] => Array ( [0] => 2 [1] => 2 [2] => 2 ) ) )
Any ideas how to be only :
Array ( [first] => Array ( [0] => 1 [1] => 1 [2] => 1) , [second] => Array([0] => 2, [1] => 2, [2] => 2))
?
$global_arr['third'][] = array('3.1' , '3.2', '3.3');
I don't get it - it's the same in/for all three functions.
BTW, I would use only one function like:
<?php
// $arg1 = "one", "two" or "three"
// $arg2 = ARRAY("data1.1", "data1.2", "data1.3") {
function myfunc($arg1, $arg2) {
if (!isset($my_arr)) { static $my_arr = ARRAY(); }
$my_arr[$arg1][] = $arg2;
return $my_arr; // Or code a getter and setter function
}
// Call, as often as you want - like:
myfunc('one', ARRAY('1.1', '1.2','1.3'));
myfunc('two', ARRAY('2.1', '2.2','2.3'));
$arr = myfunc('one', ARRAY('1.4', '1.5','1.6'));
print '<pre>';
var_dump($arr);
print '</pre>';
/* result:
array(2) {
["one"]=>
array(2) {
[0]=>
array(3) {
[0]=>
string(3) "1.1"
[1]=>
string(3) "1.2"
[2]=>
string(3) "1.3"
}
[1]=>
array(3) {
[0]=>
string(3) "1.4"
[1]=>
string(3) "1.5"
[2]=>
string(3) "1.6"
}
}
["two"]=>
array(1) {
[0]=>
array(3) {
[0]=>
string(3) "2.1"
[1]=>
string(3) "2.2"
[2]=>
string(3) "2.3"
}
}
}
*/
?>
Why you want to use global variable? You can simply write
function first($arr) {
$arr[] = array('first' =>
array('3' , '3', '3'));
return $arr;
}
function second($arr) {
$arr[] = array('second' =>
array('3' , '3', '3'));
return $arr;
}
function third($arr) {
$arr[] = array('third' =>
array('3' , '3', '3'));
return $arr;
}
$arr = array();
$arr = first($arr);
$arr = second($arr);
$arr = third($arr);

Categories