I'm trying to search for a substring within part of the bottom layer of a 2-layer array and return the key from the top layer. E.g. in the array below searching within "A" for "ca" would return "0" and "2" (but would miss "cattle"):
Array (
[0] => Array (
[A] => cat
[B] => horses
)
[1] => Array (
[A] => dog
[B] => cattle
)
[2] => Array (
[A] => cat
[B] => sheep
)
)
You can try like this :
$array = array(
array(
"A" => "cat",
"B" => "horse"
),
array(
"A" => "dog",
"B" => "cattle"
),
array(
"A" => "cat",
"B" => "sheep"
),
);
$result = mySearch($array, "A", "ca");
function mySearch($array, $key, $search)
{
$results = array();
foreach ($array as $rootKey => $data) {
if (array_key_exists($key, $data)) {
if (strncmp($search, substr($data[$key], 0, 2), strlen($search)) == 0) {
$results[] = $rootKey;
}
}
}
return $results;
}
var_dump($result);
Will output :
array(2) {
[0]=>
int(0)
[1]=>
int(2)
}
Note that this method is not encoding safe (you may use mb_str* instead of str* function family, more details here).
Related
In PHP we do have function array_flip for exchanging all keys with their associated values in an array, however I am looking for a the solution as follows with the help of php functions
INPUT
array(
"a" => 1,
"b" => 1,
"c" => 2
);
OUTPUT
array(
1 => array("a", "b"),
2 => "c"
);
I don't think there is a php function for it, so you'll have to write your own. If you really want a mixture of nested arrays and values the way to go would be:
function my_array_flip($arr)
{
$new_arr = array();
foreach ($arr as $k => $v)
{
if (array_key_exists($v, $new_arr))
{
if (is_array($new_arr[$v]))
{
$new_arr[] = $k;
}
else
{
$new_arr[$v] = array($new_arr[$v]);
$new_arr[$v][] = $k;
}
}
else
{
$new_arr[$v] = $k;
}
}
return $new_arr;
}
For your array this will return:
Array
(
[1] => Array
(
[0] => a
[1] => b
)
[2] => c
)
$source = array(
"a" => 1,
"b" => 1,
"c" => 2
);
foreach ($source as $key => $value)
{
$result[$value][] = $key;
}
Don't think exists a function for that but you can achieve it with some code:
$input = [
"a" => 1,
"b" => 1,
"c" => 2,
];
$grouped = [];
foreach ($input as $key => $group) {
$grouped[$group][] = $key;
}
Result:
var_dump($grouped);
array(2) {
[1] =>
array(2) {
[0] =>
string(1) "a"
[1] =>
string(1) "b"
}
[2] =>
array(1) {
[0] =>
string(1) "c"
}
}
Sets always array as values because I guess this will simplify things when you'll use the result in your code.
I am trying to update each language as a multidimensional array to another multidimensional array but it seems to be only saving the last key e.g.(lang_3) but not lang_1 & lang_2. Cracking my head to figure this out. Hope someone can point out my faults. ($country_specs = list of language, $get_code = country code)
$awards = array(
'award_year' => sanitize_array_text_field($_POST['award_year']),
'award_title_user' => sanitize_array_text_field($_POST['award_title_user']),
'award_description_user' => sanitize_array_text_field($_POST['award_description_user'])
);
foreach ($country_specs as $specs => $value) {
if ($value[0] == $get_code ) {
foreach ($value['lang'] as $lang_key => $lang) {
$awards_title = 'award_title_'.$lang_key;
$awards_description = 'award_description_'.$lang_key;
$awards_lang = array(
$awards_title => sanitize_array_text_field($_POST[$awards_title]),
$awards_description => sanitize_array_text_field($_POST[$awards_description])
);
update_user_meta($user_id, 'awards', array_merge($awards,$awards_lang));
}
}
}
Current code output example:
Array (
[award_year] => Array (
[0] => 1999-01
[1] => 2010-02 )
[award_title_user] => Array (
[0] => 2
[1] => tt )
[award_description_user] => Array (
[0] => 2
[1] => ddd )
[award_title_lang3] => Array (
[0] => 2CC
[1] => zz )
[award_description_lang3] => Array (
[0] => 2CCCCCCC
[1] => dzz ) )
Working code as follows.
$awards = array(
'award_year' => sanitize_array_text_field($_POST['award_year']),
'award_title_user' => sanitize_array_text_field($_POST['award_title_user']),
'award_description_user' => sanitize_array_text_field($_POST['award_description_user'])
);
$awards_new_lang = array();
foreach ($country_specs as $specs => $value) {
if ($value[0] == $get_code ) {
foreach ($value['lang'] as $lang_key => $lang) {
$awards_title = 'award_title_'.$lang_key;
$awards_description = 'award_description_'.$lang_key;
$awards_new_lang[$awards_title] = sanitize_array_text_field($_POST[$awards_title]);
$awards_new_lang[$awards_description] = sanitize_array_text_field($_POST[$awards_description]);
}
}
}
$array_merge_new = array_merge($awards, $awards_new_lang);
update_user_meta($user_id, 'awards', $array_merge_new);
I created a new array ($awards_new_lang) and did an array merge with the old array, thus combining both of the arrays together.
Try this code, it outputs as expected, I tried the mimic the variables structures
<?php
$awards = array(
'award_year' => '1999',
'award_title_user' => '2',
'award_description_user' => '2CCCCCCC'
);
$value = array();
$value['lang'] = array(1, 2, 3);
foreach ($value['lang'] as $lang_key) {
$awards_title = 'award_title_'.$lang_key;
$awards_description = 'award_description_'.$lang_key;
$awards_lang = array(
$awards_title => "$lang_key title",
$awards_description => "$lang_key desc"
);
//array merge returns an array, we save the changes here to use them later when the loops are through
$awards = array_merge($awards,$awards_lang);
}
echo '<pre>';
//Final updated version of the array
var_dump($awards);
echo '</pre>';
?>
Outputs:
array(9) {
["award_year"]=>
string(4) "1999"
["award_title_user"]=>
string(1) "2"
["award_description_user"]=>
string(8) "2CCCCCCC"
["award_title_1"]=>
string(7) "1 title"
["award_description_1"]=>
string(6) "1 desc"
["award_title_2"]=>
string(7) "2 title"
["award_description_2"]=>
string(6) "2 desc"
["award_title_3"]=>
string(7) "3 title"
["award_description_3"]=>
string(6) "3 desc"
}
This is my array :
Array
(
[0] => Array
(
[0] => S No.
[1] => Contact Message
[2] => Name
[3] => Contact Number
[4] => Email ID
)
[1] => Array
(
[0] => 1
[1] => I am interested in your property. Please get in touch with me.
[2] => lopa <br/>(Individual)
[3] => 1234567890
[4] => loperea.ray#Gmail.com
)
[2] => Array
(
[0] => 2
[1] => This user is looking for 3 BHK Multistorey Apartment for Sale in Sohna, Gurgaon and has viewed your contact details.
[2] => shiva <br/>(Individual)
[3] => 2135467890
[4] => sauron82#yahoo.co.in
)
)
How can I retrieve all data element wise?
You can get information about arrays in PHP on the official PHP doc page
You can access arrays using square braces surrounding the key you like to select [key].
So $array[1] will give yoo:
Array
(
[0] => 1
[1] => I am interested in your property. Please get in touch with me.
[2] => lopa <br/>(Individual)
[3] => 1234567890
[4] => loperea.ray#Gmail.com
)
And $array[1][2] will give you:
lopa <br/>(Individual)
Or you can walkt through the elements of an array using loops like the foreach or the for loop.
// perfect for assoc arrays
foreach($array as $key => $element) {
var_dump($key, $element);
}
// alternative for arrays with seamless numeric keys
$elementsCount = count($array);
for($i = 0; $i < $elementsCount; ++$i) {
var_dump($array[$i]);
}
You have integer indexed elements in multidimensional array. To access single element from array, use array name and it's index $myArray[1]. To get inner element of that previous selected array, use second set of [index] - $myArray[1][5] and so on.
To dynamically get all elements from array, use nested foreach loop:
foreach ($myArray as $key => $values) {
foreach ($values as $innerKey => $value) {
echo $value;
// OR
echo $myArray[$key][$innerKey];
}
}
The solution is to use array_reduce:
$header = array_map(
function() { return []; },
array_flip( array_shift( $array ) )
); // headers
array_reduce( $array , function ($carry, $item) {
$i = 0;
foreach( $carry as $k => $v ) {
$carry[$k][] = $item[$i++];
}
return $carry;
}, $header );
First of all we get the header from the very first element of input array. Then we map-reduce the input.
That gives:
$array = [['A', 'B', 'C'], ['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ['a3', 'b3', 'c3']];
/*
array(3) {
'A' =>
array(3) {
[0] =>
string(2) "a1"
[1] =>
string(2) "a2"
[2] =>
string(2) "a3"
}
'B' =>
array(3) {
[0] =>
string(2) "b1"
[1] =>
string(2) "b2"
[2] =>
string(2) "b3"
}
'C' =>
array(3) {
[0] =>
string(2) "c1"
[1] =>
string(2) "c2"
[2] =>
string(2) "c3"
}
}
*/
I think this is what you are looking for
$array = Array
(
0=> Array
(
0 => 'S No.',
1 => 'Contact Message',
2 => 'Name',
3 => 'Contact Number',
4 => 'Email ID'
),
1 => Array
(
0 => 1,
1 => 'I am interested in your property. Please get in touch with me.',
2 => 'lopa <br/>(Individual)',
3 => '1234567890',
4 => 'loperea.ray#Gmail.com',
),
2 => Array
(
0 => 2,
1 => 'This user is looking for 3 BHK Multistorey Apartment for Sale in Sohna, Gurgaon and has viewed your contact details.',
2 => 'shiva <br/>(Individual)',
3 => '2135467890',
4 => 'sauron82#yahoo.co.in',
)
);
$result_array = array();
array_shift($array);
reset($array);
foreach($array as $x=>$array2){
foreach($array2 as $i => $arr){
if($i == 1){
$result_array[$x]['Contact Message'] = $arr;
}elseif($i == 2){
$result_array[$x]['Name'] = $arr;
}elseif($i == 3){
$result_array[$x]['Contact Number'] =$arr;
}elseif($i == 4){
$result_array[$x]['Email ID'] = $arr;
}
}
}
print_r($result_array);
I want to apologize in advanced if this was already asked, I'm not exactly sure what this would be called.
I'm storing data from a form into a MongoDB database and I'd like to create defined key-value pairs to make sorting easier.
Using this code I am able to do this with a one-dimensional array, but it does not work with multidimensional arrays:
/* $array = The array */
$new_array = array();
foreach ($array as $key => $value) {
array_push($new_array, array(
'name' => $key,
'value' => $value
));
}
Example:
Input array:
Array
(
[email] => test#mail.com
[name] => John
[sports] => Array
(
[outdoor] => Array
(
[0] => Football
[1] => Baseball
)
[indoor] => Array
(
[0] => Basketball
[1] => Hockey
)
)
)
Output array:
Array
(
[0] => Array
(
[name] => email
[value] => test#mail.com
)
[1] => Array
(
[name] => name
[value] => John
)
[2] => Array
(
[name] => sports
[value] => Array
(
[outdoor] => Array
(
[0] => Football
[1] => Baseball
)
[indoor] => Array
(
[0] => Basketball
[1] => Hockey
)
)
)
)
Notice how it stops at the sports value array and does not change the array within it. How can I continue this pattern throughout all the arrays within it?
You can use recursion:
function keyValue($array){
$new_array = array();
foreach ($array as $key => $value) {
array_push($new_array, array(
'name' => $key,
'value' => is_array($value) ? keyValue($value) : $value
));
}
return $new_array;
}
Try this on for size:
$array = array(
'email' => 'test#email.com',
'name' => 'John',
'sport' => array('Soccor', 'Hockey')
);
$func = function($value, $key) {
$return = array();
$return['name'] = $key;
$return['value'] = $value;
return $return;
};
$parsed = array_map($func, $array, array_keys($array));
For me, this returned:
array(3) {
[0]=>
array(2) {
["name"]=>
string(5) "email"
["value"]=>
string(14) "test#email.com"
}
[1]=>
array(2) {
["name"]=>
string(4) "name"
["value"]=>
string(4) "John"
}
[2]=>
array(2) {
["name"]=>
string(5) "sport"
["value"]=>
array(2) {
["outdoor"]=>
array(2) {
[0]=>
string(8) "Football"
[1]=>
string(8) "Baseball"
}
["indoor"]=>
array(2) {
[0]=>
string(10) "Basketball"
[1]=>
string(6) "Hockey"
}
}
}
}
It is pretty simple to turn associative arrays to JSON objects (StdClass) and vice versa, preserving native data types (int, float, bool). Here's my attempt:
To Key-Value Array
function toKeyValue($values)
{
$result = [];
foreach ($values as $key => $value)
{
if (is_array($value)) {
$result[$key] = toKeyValue($value);
} elseif (is_object($value)) {
$result[$key] = toKeyValue((array) $value);
} else {
$result[$key] = $value;
}
}
return $result;
}
To JSON Object
function toJson($values)
{
return json_decode(json_encode($values));
}
$values should always be an array.
This is pretty basic, but my question is:
Given an array:
$a = array(
0 => array('Rate'=> array('type_id'=>1, 'name' => 'Rate_1', 'type'=>'day','value'=>10)),
1 => array('Rate'=> array('type_id'=>1, 'name' => 'Rate_2', 'type'=>'night','value'=>8)),
2 => array('Rate'=> array('type_id'=>2, 'name' => 'Rate_3', 'type'=>'day','value'=>7)),
3 => array('Rate'=> array('type_id'=>2, 'name' => 'Rate_4', 'type'=>'nigh','value'=>16)),
4 => array('Rate'=> array('type_id'=>3, 'name' => 'Rate_5', 'type'=>'day','value'=>10))
);
What is the most efficient way to change it so we have something like:
$new_array = array(
[type_id] => array(
[type] => array(
[value]
)
)
)
);
In other words, I would like to strip some data (the name, which I don't need) and reorganise the dimensions of the array. In the end I would have an array which I would be able to access the values by $new_array['type_id']['type']['value'].
Not entirely sure if this is exactly what you want, but with this you can access the values by saying
echo $new[TYPE_ID][DAY_OR_NIGHT];
$new = array();
foreach($a AS $b){
$c = $b['Rate'];
$new[$c['type_id']][$c['type']] = $c['value'];
}
Using print_r on $new would give you:
Array
(
[1] => Array
(
[day] => 10
[night] => 8
)
[2] => Array
(
[day] => 7
[night] => 16
)
[3] => Array
(
[day] => 10
)
)
Since php 5.3.0, array_reduce() allows using an array as the initial value, given your initial array $a, you can use the following code
function my_reducer ($result, $item) {
$result[$item['Rate']['type_id']][$item['Rate']['type']] = $item['Rate']['value'];
return $result;
}
$assoc_arr = array_reduce($a, 'my_reducer', array());
var_dump($assoc_arr);
This returns
array(3) { [1]=> array(2) {
["day"]=>
int(10)
["night"]=>
int(8) } [2]=> array(2) {
["day"]=>
int(7)
["nigh"]=>
int(16) } [3]=> array(1) {
["day"]=>
int(10) } }