Modify array in loop using php - php

I have a php multidimensional array(A) and I want to build another array(B) from that array A
My code is
$question = array(
"ques_15" => array(
"name" => array(
"0" => "aaa"
)
),
"ques_16" => array(
"name" => array(
"0" => "bbb",
"1" => "ccc"
)
)
);
$i=0;
foreach($question as $k=>$v)
{
list(,$qid) = explode("_",$k);
$filename .= $question[$k]['name'][$i]."#&";
$insertData[] = array(':quid'=>$qid,':answer'=>$filename);
$i++;
}
echo '<pre>';
print_r($insertData);
echo '</pre>';
It prints
Array
(
[0] => Array
(
[:quid] => 15
[:answer] => aaa#&
)
[1] => Array
(
[:quid] => 16
[:answer] => aaa#&ccc#&
)
)
But I want it to be
Array
(
[0] => Array
(
[:quid] => 15
[:answer] => aaa
)
[1] => Array
(
[:quid] => 16
[:answer] => aaa#&ccc
)
)

$i=0;
foreach($question as $k=>$v)
{
list(,$qid) = explode("_",$k);
$insertData[$i][':quid'] = $qid;
$insertData[$i][':answer'] = implode('#&',$v['name']);
$i++;
}

$filename .= (empty($filename) ? '' : '#&') . $question[$k]['name'][$i];
If aaa#&ccc is a typo and it should be bbb#&ccc, then you can simply do:
foreach($question as $k=>$v)
{
list(,$qid) = explode("_",$k);
$filename = implode("#&", $v['name']);
$insertData[] = array(':quid'=>$qid,':answer'=>$filename);
}

Remove "#&" and place it in condition. It will work;
Just Add a condition.
$filename .= $question[$k]['name'][$i];
if(!empty($filename)){
$filename .= '#&';
}

Related

value is not inserting into array properly

It is correctly insert the value of $name[$init] into the key dsf under the $val['dsf'] but it is inerting only the last value in dsf under the $val['customProduct']['dsf']
$name = array(0=>'Amit',1=>'Amit1',2=>'Amit2');
foreach($order->orderLines as $init =>$val){
$val['dsf'] = $name[$init];
$val['customProduct']['dsf'] = $name[$init];
}
You need the $val pass by reference:
$name = array(0=>'Amit',1=>'Amit1',2=>'Amit2');
$orderLines = array(
array(
'dsf' => array(),
'customProduct' => array()
),
array(
'dsf' => array(),
'customProduct' => array()
),
array(
'dsf' => array(),
'customProduct' => array()
),
);
foreach($orderLines as $init => &$val){ //edit here
$val['dsf']= $name[$init];
$val['customProduct']['dsf'] = $name[$init];
}
print_r($orderLines);
Output:
Array
(
[0] => Array
(
[dsf] => Amit
[customProduct] => Array
(
[dsf] => Amit
)
)
[1] => Array
(
[dsf] => Amit1
[customProduct] => Array
(
[dsf] => Amit1
)
)
[2] => Array
(
[dsf] => Amit2
[customProduct] => Array
(
[dsf] => Amit2
)
)
)
See here
Please Try This and In Case If You Have Any Query Just Comment I Am Happy To Answer
<?php
$name = array(0=>'Amit',1=>'Amit1',2=>'Amit2');
$orderLines = array(
array(
"id"=>1,
"order_id"=>10,
"dfs"=>0,
"customProduct"=>array(
"id"=>102,
"order_id"=>10,
"dfs"=>0,
"name"=>""
)
),
array(
"id"=>2,
"order_id"=>20,
"dfs"=>1,
"customProduct"=>array(
"id"=>105,
"order_id"=>20,
"dfs"=>1,
"name"=>""
)
),
array(
"id"=>3,
"order_id"=>50,
"dfs"=>2,
"customProduct"=>array(
"id"=>107,
"order_id"=>50,
"dfs"=>2,
"name"=>""
)
)
);
$orderLinestemp = array();
foreach($name as $value){
$temp_array = array("dfs"=>$value,"customProduct"=>array("name"=>$value));
array_push($orderLinestemp, $temp_array);
}
$orderLines=array_replace_recursive($orderLines,$orderLinestemp);
echo "<pre/>";
print_r($orderLines);
?>
output

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);

php array flip value as key and make it simple

i have been troubling to format array correctly
i have this code:
require('simple_html_dom.php');
$table = array();
$html = file_get_html('apc.html');
foreach($html->find('tr') as $row) {
$rack = ltrim($row->find('td',0)->plaintext);
$location = ltrim($row->find('td',1)->plaintext);
$usage = ltrim($row->find('td',2)->plaintext);
$auk = ltrim($row->find('td',3)->plaintext);
$cost = ltrim($row->find('td',4)->plaintext);
$rack = rtrim($rack);
$location = rtrim($location);
$usage = rtrim($usage);
$auk = rtrim($auk);
$cost = rtrim($cost);
$table[$rack][$usage][$auk][$cost] = true;
}
echo '<pre>';
print_r($table);
echo '</pre>';
using simple_html_dom above i can convert html table to an array as follow:
[Rack01] => Array
(
[741,60] => Array
(
[1.409,04] => Array
(
[267,72] => 1
)
)
[110,88] => Array
(
[210,67] => Array
(
[40,03] => 1
)
)
)
[Rack 09] => Array
(
[843,84] => Array
(
[1.603,30] => Array
(
[304,63] => 1
)
)
)
I would like to have result as below:
array(
[0] => array (
[usage] => 'Rack 01',
[usage] => '741,60',
[auk] => '1.409.04',
[cost] => '267,72')
[1] => array (
[usage] => 'Rack 02',
[usage] => 'value???',
[auk] => 'value???',
[cost] => 'value???')
any help would be apreaciate
Something like this. Also note that trim will do both left and right:
foreach($html->find('tr') as $row) {
$rack = trim($row->find('td',0)->plaintext);
$location = trim($row->find('td',1)->plaintext);
$usage = trim($row->find('td',2)->plaintext);
$auk = trim($row->find('td',3)->plaintext);
$cost = trim($row->find('td',4)->plaintext);
$table[] = array('rack' => $rack,
'usage' => $usage,
'auk' => $auk,
'cost' => $cost);
}

How do i get the final array?

I have a array here:
$array = array(
array('t'=>'t1','v'=>'001'),
array('t'=>'t2','v'=>'002'),
array('t'=>'t3','v'=>'003'),
array('t'=>'t1','v'=>'004'),
array('t'=>'t4','v'=>'005'),
array('t'=>'t2','v'=>'006'),
array('t'=>'t5','v'=>'007'),
array('t'=>'t3','v'=>'008'),
);
The final array i want is this :
array(
't1' => array('v'=>array(001,004)),
't2' => array('v'=>002),
't3' => array('v'=>array(003,008)),
't4' => array('v'=>005),
't5' => array('v'=>006),
't6' => array('v'=>007)
)
Is there any way i can achieve the final array using php array manipulation functions? I don't want to use any loops (for or foreach). Tried doing using usort() but getting no where
Here is my usort code that calls user defined function:
public function sort($a,$b)
{
$const = array();
$temp1 = array();
$temp2 = array();
//echo $a['t'].":".$a['v'] . " - " . $b['t'].":".$b['v']. "<br/>";
if($a['t'] == $b['t']){
$temp1[$a['t']] = array($a['v'],$b['v']);
//$const = $temp1;
}else{
if(!array_key_exists($a['t'],$temp1) && !array_key_exists($b['t'],$temp1)){
$temp2[$a['t']] = array($a['v']);
$temp2[$b['t']] = array($b['v']);
}
}
$result = array_merge($temp1, $temp2);
print_r($result);
}
$array = array(
array('t'=>'t1','v'=>'001'),
array('t'=>'t2','v'=>'002'),
array('t'=>'t3','v'=>'003'),
array('t'=>'t1','v'=>'004'),
array('t'=>'t4','v'=>'005'),
array('t'=>'t2','v'=>'006'),
array('t'=>'t5','v'=>'007'),
array('t'=>'t3','v'=>'008'),
);
$res = array();
foreach($array as $val){
$res[$val['t']]['v'][] = $val['v'];
}
echo "<pre>";
print_r($res);
Output :
Array
(
[t1] => Array
(
[v] => Array
(
[0] => 001
[1] => 004
)
)
[t2] => Array
(
[v] => Array
(
[0] => 002
[1] => 006
)
)
[t3] => Array
(
[v] => Array
(
[0] => 003
[1] => 008
)
)
[t4] => Array
(
[v] => Array
(
[0] => 005
)
)
[t5] => Array
(
[v] => Array
(
[0] => 007
)
)
)
<?php
$array = array(
array('t'=>'t1','v'=>'001'),
array('t'=>'t2','v'=>'002'),
array('t'=>'t3','v'=>'003'),
array('t'=>'t1','v'=>'004'),
array('t'=>'t4','v'=>'005'),
array('t'=>'t2','v'=>'006'),
array('t'=>'t5','v'=>'007'),
array('t'=>'t3','v'=>'008'),
);
foreach ($array as $key => $row) {
$t[$key] = $row['t'];
$v[$key] = $row['v'];
}
array_multisort($v, SORT_ASC, $array);
$reqArray = array();
foreach($array as $value)
{
$reqArray[$value['t']]['v'][] = $value['v'];
}
print_r($reqArray);
?>
Try with:
$input = array( /* your data */ );
$output = array();
foreach ( $input as $value ) {
$t = $value['t'];
$v = $value['v'];
if ( !isset($output[$t]) ) {
$output[$t] = array('v' => $v);
} else if ( is_array($output[$t]['v']) ) {
$output[$t]['v'][] = $v;
} else {
$output[$t]['v'] = array($output[$t]['v'], $v);
}
}

PHP how to join to records from array

Hi it is any way to connect to records where value is the same?
like
[12]=> Array (
[ID] => 127078
[row1] =>
[post] => N16 7UJ
)
[13]=> Array (
[ID] => 127078
[row1] => something
[post] =>
)
and make like that
[12]=> Array (
[ID] => 127078
[row1] => something
[post] => N16 7UJ
)
Here take this function
<?php
$array = array(
12 => array (
"ID" => '127078',
"row1" => '',
"post" => 'N16 7UJ',
),
13 => array (
"ID" => '127078',
"row1" => 'something',
"post" => '',
)
);
function mergedup($array,$matcher){
if(!function_exists('remove_element')){
function remove_element($arr,$element){
$ret_arr = array();
foreach($arr as $val){
if($val !== $element){
array_push($ret_arr,$val);
}
}
return $ret_arr;
}
}
$array = remove_element($array,array());
$return_array = array();
while(isset($array[0])){
$temp = $array[0];
$array = remove_element($array,$temp);
$array_temp = array();
foreach($array as $vals){
if($temp[$matcher]==$vals[$matcher]){
array_push($array_temp,$vals);
foreach($temp as $key => $val){
if(empty($temp[$key])){
$temp[$key] = $vals[$key];
}
}
}
}
foreach($array_temp as $vals){
$array = remove_element($array,$vals);
}
array_push($return_array,$temp);
}
return $return_array;
}
var_dump(mergedup($array,"ID"));
?>
Tested and working
You have so many option such as array_replace
array_merge
foreach
while
Iterator
But i prefer array_replace because you can easily select which array is replacing which
Values
$array[12] = array("ID"=>127078,"row1"=>"","post"=>"N16 7UJ");
$array[13] = array("ID"=>127078,"row1"=>"something","post"=>"");
var_dump($array[12]);
Example array_replace ( http://www.php.net/manual/en/function.array-replace.php )
$array[13] = array_filter($array[13]); //Filter Replacement
$array[12]= array_replace($array[12],$array[13]);
Example array_merge ( http://php.net/manual/en/function.array-merge.php )
//$array[12] = array_filter($array[12]); //Optinal
$array[13] = array_filter($array[13]); //Filter Spaces
$array[12]= array_merge($array[12],$array[13]);
var_dump($array[12]);
Output
array
'ID' => int 127078
'row1' => string 'something' (length=9)
'post' => string 'N16 7UJ' (length=7)

Categories