How to merge these two array? - php

These are my two arrays:
$test = array(
"0" => array(
"mem_id" => "299",
"profilenam" => "Guys&Dolls",
"photo_b_thumb" => "photos/935a89f58ef2f3c7aaaf294cb1461d64bth.jpeg"
),
"1" => array(
"mem_id" => "344",
"profilenam" => "Dmitry",
"photo_b_thumb" => "no")
);
$distance = array(
"0" => "0",
"1" => "3.362",
"2" => "0.23"
);
I want to combine them as:
Array
(
[0] => Array
(
[mem_id] => 299
[profilenam] => Guys&Dolls
[photo_b_thumb] => photos/935a89f58ef2f3c7aaaf294cb1461d64bth.jpeg
[distance] => 3.362
)
[1] => Array
(
[mem_id] => 344
[profilenam] => Dmitry
[photo_b_thumb] => no
[distance] => 0.23
)
)
I tried the code below but it did not work:
foreach ($test as $key => $value) {
$merged = array_merge((array) $value, $distance);
}
print_r($merged);

<?php
foreach($test as $index=>$array)
{
$test[$index]['distance'] = $distance[$index]
}
print_r($test);
?>

$test = array("0" => array("mem_id" => "299", "profilenam" => "Guys&Dolls", "photo_b_thumb" => "photos/935a89f58ef2f3c7aaaf294cb1461d64bth.jpeg"
), "1" => array("mem_id" => "344", "profilenam" => "Dmitry", "photo_b_thumb" => "no"));
$distance = array("0" => "0", "1" => "3.362", "2" => "0.23");
foreach( $test as $id => $data ) {
$test[$id]['distance'] = $distance[$id];
}
Something like this should work!

foreach ($test as $key => &$value) {
$value["distance"] = $distance[$key];
}

I think array_merge_recursive does what you need.
EDIT: It does not. :) However, a derivate of it, posted in the array_map_recursive man page does seem to, see this codepad. I'd be interested to know which is faster over a large dataset.

foreach ($test as &$value)
{
$value['distance'] = array_shift($distance);
}

Related

How to change date format in multidimensional array and iterate all array with key

I have a multidimensional array with key and value and some key is empty also. Then I want to set a value for internal not empty array.
$oldArray = array("Lexus LS600" => array(),
"Toyota Alphard" => array(),
"Benz S550" => array(0 => array(
"card_no" => "G2FPCBS3",
"travel_date" => "2020-09-10"
"travel_time" => "16:15:00",
"car_id" => 12,
"return_time" => "17:25")),
"BMW X6" => array());
I had this array but I want to set return_time 00:00 all over array. I tried foreach loop but foreach is remove empty array but I want empty array also.
I want this type array:-
$newArray = array("Lexus LS600" => array(),
"Toyota Alphard" => array(),
"Benz S550" => array(0 => array(
"card_no" => "G2FPCBS3",
"travel_date" => "2020-09-10"
"travel_time" => "16:15:00",
"car_id" => 12,
"return_time" => "00:00")),
"BMW X6" => array());
Try this foreach again, I think it will solve your problem if I understood you correctly.
foreach ($arrays as $key => $values) {
if (is_array($values)) {
if (count($values)) {
foreach ($values as $index => $data) {
$arrays[$key][$index]['return_time'] = "00:00";
}
} else {
$arrays[$key] = $values;
}
}
}
It will change return_time to "00:00" and also retain the empty index to your array.
array_walk_recursive() is very suitable for this.
$oldArray = array("Lexus LS600" => array(),
"Toyota Alphard" => array(),
"Benz S550" => array(0 => array(
"card_no" => "G2FPCBS3",
"travel_date" => "2020-09-10",
"travel_time" => "16:15:00",
"car_id" => 12,
"return_time" => "17:25")),
"BMW X6" => array());
$keySearch = "return_time";
$replaceWith = "00:00";
array_walk_recursive(
$oldArray,
function(&$val,$key) use($keySearch,$replaceWith){
if($key == $keySearch) $val = $replaceWith;
}
);
var_export($oldArray);
Output:
array (
'Lexus LS600' =>
array (
),
'Toyota Alphard' =>
array (
),
'Benz S550' =>
array (
0 =>
array (
'card_no' => 'G2FPCBS3',
'travel_date' => '2020-09-10',
'travel_time' => '16:15:00',
'car_id' => 12,
'return_time' => '00:00',
),
),
'BMW X6' =>
array (
),
)
Use two foreach loops to traverse the limited-depth array and make all values modifiable by reference (& before the variable). In doing so, you don't need to create a separate array, just update the input array. It is SUPER easy to read and maintain.
Code: (Demo)
foreach ($array as &$cars) {
foreach ($cars as &$entry) {
if ($entry) {
$entry["return_time"] = "00:00";
}
}
}
var_export($array);
Output:
array (
'Lexus LS600' =>
array (
),
'Toyota Alphard' =>
array (
),
'Benz S550' =>
array (
0 =>
array (
'card_no' => 'G2FPCBS3',
'travel_date' => '2020-09-10',
'travel_time' => '16:15:00',
'car_id' => 12,
'return_time' => '00:00',
),
),
'BMW X6' =>
array (
),
)

How to extract specific key string from array in php?

This is my array
Array
(
[question_set] => Computer Basics
[question] => Who are You ?
[options_1] => RK
[options_2] => KAMAL
[options_3] => DPK
[options_4] => NARENDRA
[marks] => 5
[negative_marks] => 1
[type] => 1
)
options_ are dynamic means it can be 4, 6 or 8.
I want to get value "options" from key of options_1 or so on. How can I do this.
strpos is way faster than preg_match, for reference: strpos() vs preg_match()
Using foreach and strpos() :
$arr = array(
"question_set" => "Computer Basics",
"question" => "Who are You ?",
"options_1" => "RK",
"options_2" => "KAMAL",
"options_3" => "DPK",
"options_4" => "NARENDRA",
"marks" => 5,
"negative_marks" => 1,
"type" => 1
);
$newArr = array();
foreach($arr as $key => $value) {
if(strpos($key, "options") !== false) {
$newArr[$key] = $value;
}
}
echo '<pre>';
var_dump($newArr);
echo '</pre>';
<?php
$array = array("options_1" => "RK",
"options_213" => "21313",
"options_4" => "NARENDRA",
"foo" => "bar", 5 , 5 => 89009,
);
$pattern = "/\boptions/";
foreach($array as $key => $value) {
if (preg_match($pattern,$key)){
echo $key."\t=>\t".$value."\n";
}
}

PHP Get most repeated value in Array

I have an array within an array like this:
Array
(
[0] => Array
(
[name] => B
[id] => 924572
)
[1] => Array
(
[name] => A
[id] => 120689
)
[2] => Array
(
[name] => A
[id] => 120689
)
[3] => Array
(
[name] => C
[id] => 919644
)
[4] => Array
(
[name] => A
[id] => 120689
)
[5] => Array
(
[name] => B
[id] => 924572
)
)
How can I get the most repeated value from object named name and id?
I've already tried the code below but I'm getting an error: Warning: array_count_values(): Can only count STRING and INTEGER values!
$count = array_count_values($info);
arsort($count);
$popular = array_keys($count);
echo $popular[0];
Any fix regarding to this problem?
"Serializing way" for searching most repeated couples (name,id):
$out = array();
foreach($arr as $el){
$key = serialize($el);
if (!isset($out[$key]))
$out[$key]=1;
else
$out[$key]++;
}
arsort($out);
foreach($out as $el=>$count){
$item = unserialize($el);
echo "Name = ".$item['name'].' ID = '.$item['id'].' Count = '.$count.'<br/>';
}
Output:
Name = A ID = 120689 Count = 3
Name = B ID = 924572 Count = 2
Name = C ID = 919644 Count = 1
update Without loop
.....
arsort($out);
$most = unserialize(key($out));
$most_count = array_shift($out);
echo $most['name'];
echo $most['id'];
echo $most_count;
Output:
A
120689
3
A more linear solution.
$arr = Array
(
Array
(
"name" => "B",
"id" => 924572
),
Array
(
"name" => "A",
"id" => 120689
),
Array
(
"name" => "A" ,
"id" => 120689
),
Array
(
"name" => "C",
"id" => 919644
),
Array
(
"name" => "A",
"id" => 120689
),
Array
(
"name" => "B",
"id" => 924572
));
$countArr = Array();
for($i = 0; $i < count($arr); $i++)
{
$tmpArr = $arr[$i];
if(array_key_exists($tmpArr["name"],$countArr))
$countArr[$tmpArr["name"]]++;
else
$countArr[$tmpArr["name"]] = 0;
}
arsort($countArr);
var_dump($countArr);
Maybe you can work with this solution:
<?php
$info = array(
array(
"name" => "B",
"id" => 924572
),
array(
"name" => "A",
"id" => 120689
),
array(
"name" => "A",
"id" => 120689
),
array(
"name" => "C",
"id" => 919644
),
array(
"name" => "A",
"id" => 120689
),
array(
"name" => "B",
"id" => 924572
),
);
$result = array();
foreach ($info as $infoKey => $infoValue) {
foreach ($infoValue as $itemKey => $itemValue) {
if ($itemKey != "name") {
continue;
}
if (array_key_exists($itemValue, $result)){
$result[$itemValue]++;
continue;
}
$result[$itemValue] = 1;
}
}
arsort($result);
var_dump($result);
Will result in:
array (size=3)
'A' => int 3
'B' => int 2
'C' => int 1
Based on finding the mode and mapping in PHP. Would this work?
$name_array = array_map(function($x) {return $x["name"];}, $info);
$count = array_count_values($name_array);
$mode = array_keys($count, max($count));
To return an array of "name", "id" pairs use:
$return_value = array_filter($info, function($x) use ($mode) { return (in_array($x["name"], $mode));});
Makes use of array_column (requires PHP 5.5 or shim).
$count_values = array_count_values(array_column($array, 'name'));
$most_frequent_name = array_search(max($count_values), $count_values);
Then if you want all arrays with this name:
$items = array_filter($array, function ($v) use ($most_frequent_name) {
return $v['name'] == $most_frequent_name;
});
If several names may have the same top frequency:
$count_values = array_count_values(array_column($array, 'name'));
$most_frequent_names = array_keys($count_values, max($count_values));
$items = array_filter($array, function ($v) use ($most_frequent_names) {
return in_array($v['name'], $most_frequent_names);
});
Try following code. It will give you count of occurrences of all elements
function array_icount_values($arr,$lower=true) {
$arr2=array();
if(!is_array($arr['0'])){$arr=array($arr);}
foreach($arr as $k=> $v){
foreach($v as $v2){
if($lower==true) {$v2=strtolower($v2);}
if(!isset($arr2[$v2])){
$arr2[$v2]=1;
}else{
$arr2[$v2]++;
}
}
}
return $arr2;
}
$arr = array_icount_values($array);
echo "<pre>";
print_r($arr);

move array keys to another array

i have an array like this :
$post = array(
"name" => "John",
"user" => "1" ,
"title" => "hello" ,
"uploader_0_name" => "pic.jpg",
"uploader_0_status" => "done",
"uploader_1_name" => "aaaa.jpg",
"uploader_1_status" => "done",
"uploader_2_name" => "Tulips.jpg",
"uploader_2_status" => "failed",
"uploader_count" => "3"
);
i want to have uploader_[/d]_name and uploader_[/d]_name in another array like example :
[0] => Array
(
[name] => pic.jpg
[status] => done
)
[1] => Array
(
[name] => aaaa.jpg
[status] => done
)
[2] => Array
(
[name] => Tulips.jpg
[status] => failed
)
in this case array with index 0 should have uploader_0_name,uploader_0_status
i tried a lot to do this with preg_match in foreach loop , but i could not be successful
foreach ( $post as $key => $value ) {
$pattern = "/^uploader_[\d]_(name|status)$/";
preg_match( $pattern , $key ,$matches[]);
}
P.S : Unfortunately today i seen the best answer and the best way was deleted ,so i added it , if any one have problem like this , can use :
foreach ($post as $key => $value) {
if (preg_match('/^uploader_(\d)_(name|status)$/', $key, $matches)) {
$result[$matches[1]][$matches[2]] = $value;
}
}
try this if you dont want to use regular expressions:
$newArr = array();
foreach($post as $key => $val) {
$newKey = explode("_", $key);
if (count($newKey) > 2) {
//this is the status
$innerValue = array_pop($newKey);
//this is the numeric ID _2_ for example
$innerKey = array_pop($newKey);
$newArr[$innerKey][$innerValue] = $val;
}
}
There is a simple way to do this do not use hard structures:
$post = array(
"name" => "John",
"user" => "1" ,
"title" => "hello" ,
"uploader_0_name" => "pic.jpg",
"uploader_0_status" => "done",
"uploader_1_name" => "aaaa.jpg",
"uploader_1_status" => "done",
"uploader_2_name" => "Tulips.jpg",
"uploader_2_status" => "failed",
"uploader_count" => "3"
);
//result array;
$arr = array();
//counter
$n = 0;
foreach ($post as $key => $value) {
if(strpos($key, '_name') != false){
$arr[$n]['name'] = $value;
}elseif(strpos($key, '_status') != false){
$arr[$n]['status'] = $value;
$n++;
}
}
print_r($arr);

PHP Counting inside an Array

I want to create a list where if its already in the array to add to the value +1.
Current Output
[1] => Array
(
[source] => 397
[value] => 1
)
[2] => Array
(
[source] => 397
[value] => 1
)
[3] => Array
(
[source] => 1314
[value] => 1
)
What I want to Achieve
[1] => Array
(
[source] => 397
[value] => 2
)
[2] => Array
(
[source] => 1314
[value] => 1
)
My current dulled down PHP
foreach ($submissions as $timefix) {
//Start countng
$data = array(
'source' => $timefix['parent']['id'],
'value' => '1'
);
$dataJson[] = $data;
}
print_r($dataJson);
Simply use an associated array:
$dataJson = array();
foreach ($submissions as $timefix) {
$id = $timefix['parent']['id'];
if (!isset($dataJson[$id])) {
$dataJson[$id] = array('source' => $id, 'value' => 1);
} else {
$dataJson[$id]['value']++;
}
}
$dataJson = array_values($dataJson); // reset the keys - you don't nessesarily need this
This is not exactly your desired output, as the array keys are not preserved, but if it suits you, you could use the item ID as the array key. This would simplify your code to the point of not needing to loop through the already available results:
foreach ($submissions as $timefix) {
$id = $timefix['parent']['id'];
if (array_key_exists($id, $dataJson)) {
$dataJson[$id]["value"]++;
} else {
$dataJson[$id] = [
"source" => $id,
"value" => 1
];
}
}
print_r($dataJson);
You should simplify this for yourself. Something like:
<?
$res = Array();
foreach ($original as $item) {
if (!isset($res[$item['source']])) $res[$item['source']] = $item['value'];
else $res[$item['source']] += $item['value'];
}
?>
After this, you will have array $res which will be something like:
Array(
[397] => 2,
[1314] => 1
)
Then, if you really need the format specified, you can use something like:
<?
$final = Array();
foreach ($res as $source=>$value) $final[] = Array(
'source' => $source,
'value' => $value
);
?>
This code will do the counting and produce a $new array as described in your example.
$data = array(
array('source' => 397, 'value' => 1),
array('source' => 397, 'value' => 1),
array('source' => 1314, 'value' => 1),
);
$new = array();
foreach ($data as $item)
{
$source = $item['source'];
if (isset($new[$source]))
$new[$source]['value'] += $item['value'];
else
$new[$source] = $item;
}
$new = array_values($new);
PHP has a function called array_count_values for that. May be you can use it
Example:
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)

Categories