I'm trying to implode an array to perform insertion , but i couldn't trigger the error i did.
implode() [function.implode]: Invalid arguments passed
*Please note my array size is not fix so i used foreach*
Array structure
[attcode] => Array ( [0] => [1] => [2] => )
[color] => Array ( [0] => [1] => [2] => )
[size] => Array ( [0] => [1] => [2] => )
[stock] => Array ( [0] => [1] => [2] => )
Working code
$attstring = array();//array for storing query set
foreach($productcount['attcode'] as $attcode){
$attstring[] = "'" . implode("','", $attcode)."'";
}
foreach($productcount['color'] as $attcolor){
$attstring[] = "'" . implode("','", $attcolor)."'";
}
foreach($productcount['size'] as $attsize){
$attstring[] = "'" . implode("','", $attsize)."'";
}
foreach($productcount['stock'] as $attstock){
$attstring[] = "'" . implode("','", $attstock) . "'";
}
$finalvalue = "(" . implode("), (", $attstring) . ")";
echo $finalvalue;
Desired output
('code','color','size',stock),
('code','color','size',stock),
('code','color','size',stock)
Your array structure does not fit the desired output format. So implode won't work.
<?php
$my_array = ARRAY();
$my_array['attcode'] = Array ( 0 => 0, 1 => 1, 2 => 2);
$my_array['color'] = Array ( 0 => 'red', 1 => 'green', 2 => 'blue');
$my_array['size'] = Array ( 0 => 100, 1 => 200, 2 => 300);
$my_array['stock'] = Array ( 0 => 11, 1 => 22, 2 => 33);
$loop_me = count($my_array['attcode']) - 1;
for ($i=0; $i<=$loop_me; $i++) {
echo '<div>Code: '.$my_array['attcode'][$i].' | Color: '.$my_array['color'][$i].' | Size: '.$my_array['size'][$i].' | Stock: '.$my_array['stock'][$i].'</div>';
}
?>
Output
Code: 0 | Color: red | Size: 100 | Stock: 11 |
Code: 1 | Color: green | Size: 200 | Stock: 22 |
Code: 2 | Color: blue | Size: 300 | Stock: 33 |
Try:
implode(',', $productcount['attcode']);
//same for others
implode works with arrays not it's values, it appends the desired string with array elements. You are passing array value to implode. pls check this for detail
You left out the most important part of the error message; where it says that implode expects an array and that you've passed a string. Based on the desired output, I reckon you want something like this:
<?php
$productcount = array(
'attcode' => array ( '0', '1', '2' ),
'color' => array ( 'red', 'green', 'blue' ),
'size' => array( '0', '1', '2' ),
'stock' => array ( 100, 200, 300 )
);
$outcome = array( );
foreach( $productcount['attcode'] as $index => $code ) {
$outcome[] = array(
'attcode' => $code,
'color' => isset( $productcount['color'][$index] ) ? $productcount['color'][$index] : null,
'size' => isset( $productcount['size'][$index] ) ? $productcount['size'][$index] : null,
'stock' => isset( $productcount['stock'][$index] ) ? $productcount['stock'][$index] : null
);
}
var_dump( $outcome );
http://php.net/manual/en/function.implode.php
$attstring = array();//array for storing query set
foreach($productcount as $attributeCount){
$attstring[] = "'" . implode("','", $attributeCount)."'";
}
$finalvalue = "(" . implode("), (", $attstring) . ")";
echo $finalvalue;
I think you've build the wrong array for the output you want:
$products = array();
$products[] = array('attrcode' => 'XXXX', 'color' => 'black', 'size' => '12', 'stock' => 'yes');
$products[] = array('attrcode' => 'XXXX', 'color' => 'white', 'size' => '5', 'stock' => 'no');
$imploded_products = array();
foreach ($products as $product) {
$imploded_products[] = "'".implode("','", $product)."'";
}
$finalvalue = "(".implode("), (", $imploded_products).")";
echo $finalvalue;
Related
Array
(
[0] => Array
(
[intID] => 3
[intVolumeType] => 1
[intVolume] => 10
[totalVolumes] => 10
[intTrack] => 10
[intTrackType] => 2
[totalTracks] => 10
)
[1] => Array
(
[intID] => 4
[intVolumeType] => 2
[intVolume] => 100
[totalVolumes] => 200
[intTrack] => 111
[intTrackType] => 3
[totalTracks] => 222
)
)
I want to print above array as:
intVolumeType = 1
totalVolumes = 10
intVolumeType = 2
totalVolumes = 200
intTrackType = 2
totalTracks = 10
intTrackType = 3
totalTracks = 222
How to loop through this PHP array. There are total six elements in array. Which might increase upto 20. Print first Volume Information, than Track, and so on.Please help
try this here: http://phpfiddle.org/
<?php
$a = Array
(
0 => [
'intID' => 3,
"intVolumeType" => 1,
"intVolume" => 10,
"totalVolumes" => 10,
"intTrack" => 10,
"intTrackType" => 2,
"totalTracks" => 10,
],
1 => [
"intID" => 4,
"intVolumeType" => 2,
"intVolume" => 100,
"totalVolumes" => 200,
"intTrack" => 111,
"intTrackType" => 3,
"totalTracks" => 222,
]
);
/*echo "<pre>";
print_r( $a );
echo "</pre>";
*/
// you have to do it manually
$volume = "";
$track = "";
foreach ( $a as $item ) {
// preparing for volumes types
$volume .= "intVolumeType = " . $item['intVolumeType'] . "<br/>";
$volume .= "TotalVolumes = " . $item['totalVolumes'] . "<br/>";
// you can add other variables too
$volume .= "<br/>";
// preparing for track types
$track .= "intTrackType = " . $item['intTrackType'] . "<br/>";
$track .= "TotalTracks = " . $item['totalTracks'] . "<br/>";
// you can add other variables too
$track .= "<br/>";
}
echo $volume;
echo "===================<br/>";
echo $track;
?>
I'm processing the final results of competitions and its general report on the best trainer and which place the trainer should get.
I have already prepared associative arrays below. The key represents trainer's id and the value represents the number of medals in a category (gold, silver, bronze) that his/her athletes got.
[gold] => Array
(
[777777] => 4
[333333] => 2
[555555] => 1
[999999] => 1
)
[silver] => Array
(
[999999] => 3
[777777] => 3
[333333] => 2
)
[bronze] => Array
(
[333333] => 6
[777777] => 4
[999999] => 2
)
Next array associates trainer's id with its name:
[trainers] => Array
(
[333333] => Trainer 4
[777777] => Trainer 1
[999999] => Trainer 2
[555555] => Trainer 3
)
I have stuck processing the data above into final results like this. Any ideas on how it could be done elegantly? The problem is that the data is never constant and the size of the array is always different.
Any help would be greatly appreciated.
Here is code sample:
$gold, $silver, $bronze, $trainers are arrays with information you provided.
$out = [];
foreach($trainers as $trainerId=> $trainerName){
$out[] = array(
'id'=>$trainerId,
'name'=>$trainerName,
'gold'=>isset($gold[$trainerId])?$gold[$trainerId]:0,
'silver'=>isset($silver[$trainerId])?$silver[$trainerId]:0,
'bronze'=>isset($bronze[$trainerId])?$bronze[$trainerId]:0,
);
}
uasort($out, function($a, $b){
// Here: sort by your algorithm. Here is example:
if($a['gold'] != $b['gold']){
return $b['gold'] - $a['gold'];
}
if($a['silver'] != $b['silver']){
return $b['silver'] - $a['silver'];
}
return $b['bronze'] - $a['bronze'];
});
$placeId = 1;
foreach($out as &$info){
$info['place'] = $placeId++;
}
unset($info);
foreach($out as $info){
echo "{$info['place']} place goes to - {$info['name']} ({$info['id']}) as he/she got {$info['gold']} gold medals, {$info['silver']} silver and {$info['bronze']} bronze";
}
Here is another way to do it with metrics:
$gold = array
(
'777777' => 4,
'333333' => 2,
'555555' => 1,
'999999' => 1
);
$silver = array
(
'999999' => 3,
'777777' => 3,
'333333' => 2
);
$bronze = array
(
'333333' => 6,
'777777' => 4,
'999999' => 2
);
$trainers = array
(
'333333' => 'Trainer 4',
'777777' => 'Trainer 1',
'999999' => 'Trainer 2',
'555555' => 'Trainer 3'
);
$metrics = [
'gold' => 3,
'silver'=> 2,
'bronze' => 1];
$results = [];
foreach ($metrics as $arrName => $metric)
{
foreach (${$arrName} as $trainerId => $medals)
{
$results[$trainerId] = ( isset($results[$trainerId]) ) ? $results[$trainerId]+$medals * $metric : $medals * $metric;
}
}
// sorting scores (by value)
arsort($results);
// print scores
var_dump($results);
// print final results
$placeOut = '';
foreach ($results as $trainerId => $score) {
$placeOut .= $trainers[$trainerId].": he/she has ";
foreach ($metrics as $medalName => $metric) {
$placeOut .= (${$medalName}[$trainerId] > 0 ? ${$medalName}[$trainerId] : 0)." ".$medalName.", ";
}
$placeOut .= "\n";
}
echo "<pre>".$placeOut."</pre>";
?>
I have array like below:
Array
(
[22] => Array
(
[0] => 60
[29] => Array
(
[0] => 6
)
[30] => Array
(
[0] => 5
[1] => 8
)
[31] => Array
(
[0] => 7
[1] => 9
[2] => 14
[3] => 26
)
)
[23] => 12
[35] =>10
[42] =>22
)
now i want to implode array like
60[6][5||8][7||9||14||26]|12|10|22
I have tried below code:
$arr = array_map(function($el){ return $el['tag_id']; }, $arr);
$str = implode(',', $arr);
But it is not implode with required glue
How can i do it?
you can use this code
<?php
$a= Array(
22 => Array(
0 => 60,
29 => Array(
0 => 6
),
30 => Array
(
0 => 5,
1 => 8
),
31 => Array
(
0 => 7,
1 => 9,
2 => 14,
3 => 26
),
),
23 => 12,
35 =>10,
42 =>22,
);
$string='';
foreach($a as $arr){
if(is_array($arr)){
foreach($arr as $array){
if(is_array($array)){
$string .= '['.implode("||",$array).']';
}else{
if($string!==''){ $string .= '|';}
$string .= $array;
}
}
}else{
if($string!==''){ $string .= '|';}
$string .= $arr;
}
}
echo $string;die;
?>
Out put wil be
60[6][5||8][7||9||14||26]|12|10|22
Desired result without foreach.
$array = [
22 => [
0 => 60,
29 => [
0 => 6
],
30 => [
0 => 5,
1 => 8
],
31 => [
0 => 7,
1 => 9,
2 => 14,
3 => 26
]
],
23 => 12,
35 => 10,
42 => 22
];
$result = implode('|', array_map(function($item)
{
return is_array($item) // convert sub array into string
? implode('', array_map(function($inner_item)
{
return is_array($inner_item) // convert inner array into string
? '[' . implode('||', $inner_item) . ']'
: $inner_item;
}, $item))
: $item;
}, $array));
var_dump($result);
So, we have 3 types of delimiters: '|' - first level, ''(empty) - second level, '||' - third level.
You can use foreach and implode to achieve your pattern:
<?php
header('Content-Type: text/plain');
$arr = array();
$arr22 = array();
$arr22[0] = 60;
$arr22[29] = array(6);
$arr22[30] = array(5,8);
$arr22[31] = array(7,9,14,26);
$arr[22] = $arr22;
$arr[23] = 12;
$arr[35] = 10;
$arr[42] = 22;
$output = '';
foreach($arr as $entry) {
if(!is_array($entry)) {
$output .= $entry;
} else {
// array
foreach($entry as $inner) {
if(is_array($inner)) {
$output .= '[' . implode('||', $inner) . ']';
} else {
$output .= $inner;
}
}
}
$output .= '|';
}
echo substr($output, 0, strlen($output) - 1);
?>
which outputs:
60[6][5||8][7||9||14||26]|12|10|22
This should work for you:
Here the glue is configurable as you desired and this logic is built on the recursive call hence this will work for any level of multidimensional array:
<?php
$arrVal = array (
'22' => array(
'0' => 60,
'29' => array(
'0' => 6
),
'30' => array (
'0' => 5,
'1' => 8
),
'31' => array (
'0' => 7,
'1' => 9,
'2' => 14,
'3' => 26
)
),
'23' => 12,
'35' => 10,
'42' => 22
);
//60[6][5||8][7||9||14||26]|12|10|22
$constructedValue = "";
$glue = "||";
echo $constructedValue = implodeMultiArr($arrVal,$glue);
function implodeMultiArr($arrVal,$glue) {
$i = 0;
$constructedValue = "";
foreach ( $arrVal as $k=>$v) {
if ( is_array($v) ) {
$constructedValue .= !empty($constructedValue) ? "[".implodeMultiArr($v,$glue)."]" : implodeMultiArr($v,$glue)."]" ;
} else {
$constructedValue .= !empty($constructedValue) ? $glue.$v : $v ;
}
$i++;
}
return $constructedValue;
}
I have an array which contains following values.
array(
'dates' => array(
(int) 0 => '2013-04-22',
(int) 1 => '2013-04-23',
),
'publisherName' => array(
(int) 0 => 'Comp1',
(int) 1 => 'Comp2',
),
'loaded' => array(
(int) 0 => (int) 2189,
(int) 1 => (int) 37,
),
'clicks' => array(
(int) 0 => (int) 0,
(int) 1 => (int) 0,
),
'ctr' => array(
(int) 0 => (int) 0,
(int) 1 => (int) 0,
)
)
What I want to produce is getting company based data on different dates like the array below.
How am I able to create an array which is like;
array (
'2013-04-22'=>array(
'publisherName'=>'Comp1',
'loaded'=>2189,
'clicks'=>0,
'ctr'=>0),
'2013-04-23'=>array(
'publisherName'=>'Comp2',
'loaded'=>37,
'clicks'=>0,
'ctr'=>0)
...
)
Which contains daily stats but which comes from publishername field.
Any ideas?
Here's an example that doesn't rely on any keys, the only requirement is that date is the first array in your original array:
// $array is your original array
$dates = array_shift($array);
$output = array();
foreach ($array as $k => $a) {
foreach ($a as $i => $v) {
$output[$i][$k] = $v;
}
}
$output = array_combine($dates, $output);
Let the initial array be $a and the desired array $b;
Code:
$b = array();
$count = 0;
foreach($a['dates'] as $date) {
$b[$date] = array(
'name' => $a['publisherName'][$count],
'loaded'=> $a['loaded'][$count],
'clicks'=> $a['clicks'][$count],
'ctr'=> $a['ctr'][$count]
);
$count++;
}
Result:
Array
(
[2013-04-22] => Array
(
[name] => Comp1
[loaded] => 2189
[clicks] => 0
[ctr] => 0
)
[2013-04-23] => Array
(
[name] => Comp2
[loaded] => 37
[clicks] => 0
[ctr] => 0
)
)
<?php
$data = $yourarray;
$new = array();
foreach($data['dates'] as $key=>$value) {
$new[$value] = array('name'=>$data['publisherName'][$key],'loaded'=>$data['loaded'][$key],'clicks'=>$data['clicks'][$key],'ctr'=>$data['ctr'][$key]);
}
echo '<pre>';
print_r($new);
?>
$newArr = array();
foreach($data['dates'] as $key=>$value) {
$new[$value] = array('name'=>$data['publisherName'][$key],'loaded'=>$data['loaded'][$key],'clicks'=>$data['clicks'][$key],'ctr'=>$data['ctr'][$key]);
}
echo '<pre>';
print_r($newArr);
$new_arr = your array;
$finalArray = array();
foreach($new_arr['dates'] as $key => $value){
$finalArray[$value] = array(
'publisherName'=>$new_arr['publisherName'][$key],
'loaded'=>$new_arr['loaded'][$key],
'clicks'=>$new_arr['clicks'][$key],
'ctr'=>$new_arr['ctr'][$key]
);
}
Output :
Array
(
[2013-04-22] => Array
(
[publisherName] => Comp1
[loaded] => 2189
[clicks] => 0
[ctr] => 0
)
[2013-04-23] => Array
(
[publisherName] => Comp2
[loaded] => 37
[clicks] => 0
[ctr] => 0
)
)
Array
(
[pid] => Array
(
[0] => 2
[1] => 3
)
[price] => Array
(
[0] => 20
[1] => 20
)
[qty] => Array
(
[0] => 2
[1] => 1
)
)
i have an outcome of the above array from some processing. with this i need to update to database like below table
pid price qty
2 20 2
3 20 1
$i = 0;
while( $i < count( $YourArray['pid']) ) {
$query = "INSERT INTO `tableName`(`pid`, `price`, `qty`) VALUES( ?, ?, ? )";
$stmt = $con->prepare( $query );
$stmt->execute(
array(
$YourArray['pid'][$i],
$YourArray['price'][$i],
$YourArray['qty'][$i]
)
);
$i++;
}
Where, I used the pdo method of insertion.
for(i=0;i<amount;i++){
echo $array['pid'][i];
echo $array['price'][i];
echo $array['qty'][i];
}
Where amount must be a count of the amount of rows you have
Try this :
$array = array("pid" => array(2,3),"price" => array(20,20),"qty" => array(2,1));
array_unshift($array, null);
$res = call_user_func_array('array_map', $array);
echo "<pre>";
print_r($res);
Output :
Array
(
[0] => Array
(
[0] => 2
[1] => 20
[2] => 2
)
[1] => Array
(
[0] => 3
[1] => 20
[2] => 1
)
)
loop this array and add to DB - So that you can add two entries in DB
this is a wrong way of doing it, i would use an indexed array, and then build a foreach loop that will handle each 1 separately, something like:
$values = array();
$values[] = array(
'pid' => 2,
'price' => 20,
'qty' => 2
);
$values[] = array(
'pid' => 3,
'price' => 20,
'qty' => 1
);
and from this then build a foreach loop and run each query there
foreach ($values as $value) {
$query = "insert into blah
set pid = " . $value['pid'] . ",
price = " . $value['price'] . ",
qty = " . $value['qty'] . ";";
mysql_query($query);
}