Loop through Array, with Similar items First in PHP - php
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;
?>
Related
Using array after POST
I would like to edit database entries with a simple form. The id and name of each entry is fixed. Problems: After submitting the form $farray does only include the edited data of $array[3] not of the other records. $farray doesn't include name and id (not included in the form). I need the id of the record for the query. What could I use as a workaround? Current script <?php $query = mysql_query("SELECT * FROM database"); $array = array(); while($row = mysql_fetch_assoc($query)){ $array[] = $row; } if(isset($_POST['send'])) { $farray = $_POST['farray']; foreach ($farray as $key => $value) { echo('UPDATE database SET ' . $key . ' = "' . $value . '"' . ' WHERE id = ' . $farray['id']); //testing } } ?> <form action=" <?=$_SERVER['PHP_SELF']?> " method="POST"> <?php foreach($array as $key1){ echo $key1["name"] . "<br />"; foreach($key1 as $key => $value){ if ($key != "id" AND $key != "name") { print $key. ' <input type="text" name="farray['.$key.']" value="'.$value.'"><br /><br />'; } } } ?> <input type="submit" name="send" value="send"> </form> Example $array Array ( [0] => Array ( [id] => 0 [name] => name0 [1] => 1 [2] => 2 [3] => 3 ) [1] => Array ( [id] => 1 [name] => name1 [1] => 1 [2] => 2 [3] => 3 ) [2] => Array ( [id] => 2 [name] => name2 [1] => 1 [2] => 2 [3] => 3 ) [3] => Array ( [id] => 3 [name] => name3 [1] => 1 [2] => 2 [3] => 3 ) ) Example $farray (after editing and submitting form) Array ( [1] => 10 [2] => 20 [3] => 30 )
OK, even though your table fields are not 1, 2, and 3, you just needed to change up your posted array a little. So I made you a little example: <form method="post"> <?php // Simulate DB records $array = [ [ 'id' => 0, 'name' => 'name0', '1' => 1, '2' => 2, '3' => 3 ], [ 'id' => 1, 'name' => 'name1', '1' => 1, '2' => 2, '3' => 3 ], [ 'id' => 2, 'name' => 'name2', '1' => 1, '2' => 2, '3' => 3 ] ]; // Create the input fields: foreach( $array as $key1 ) { echo $key1["name"] . "<br />"; foreach($key1 as $key => $value) { if ($key != "id" AND $key != "name") { echo $key. ' <input type="text" name="farray[' . $key1['id'] . ']['.$key.']" value="'.$value.'"><br /><br />'; } } } ?> <button type="submit">Submit</button> </form> <pre> <?php if( isset( $_POST['farray'] ) ) { print_r( $_POST ); foreach( $_POST['farray'] as $id => $values ) { foreach( $values as $k => $v ) { echo('UPDATE database SET ' . $k . ' = "' . $v . '"' . ' WHERE id = ' . $id ) . '<br />'; } } } ?> </pre> I tested this, and I think it works as you would expect.
Use array_search but continue searching after result found (PHP)
I have been playing around with array_search. I have been trying to search an array and get details from it. The problem is, once it finds the result it moves on, it doesn't check for duplicates in the array. I can't seem to work out my loop logic, any suggestions? The $names array Array( [0] => Array ( [name] => Fred [age] => 20 ) [1] => Array ( [name] => George [age] => 17 ) [2] => Array ( [name] => Sarah [age] => 22 ) [3] => Array ( [name] => Fred [age] => 30 ) ) $name=" Fred"; //loop here $array_position = array_search($name, array_column($names, 'name')); $array_data = $names[$array_position]; echo $array_data['name'] . " is: " . $array_data['age'] . " years old. //end loop Result: Fred is 20 years old. Expected result: Fred is 20 years old Fred is 30 years old. I tried array_keys() but I don't understand php.net very well Should I try store the results in a separate array and then loop that to print? Seems like there should be a more efficient/elegant solution.
use array_filter to find all. function search($array, $key) { return array_filter($array, function($v) use($key){return $v['name'] == $key;}); } $result = search($array, $key); foreach($result as $v) { echo $v['name'] . " is: " . $v['age'] . " years old."; }
#Ben first of all array_search() return true or false not the key, but for your desired output you can simply try with foreach() with a condition like below or with array_key: with foreach() <?php $names = array(0 => array( "name" => "Fred", "age" => 20 ), 1 => array( "name" => "George", "age" => 17 ), 2 => array( "name" => "Sarah", "age" => 22 ), 3 => array( "name" => "Fred", "age" => 30 ) ); $name= "Fred"; echo "<pre>"; foreach($names as $val){ if($val["name"] == $name){ echo $name . " is: " . $val["age"] . " years old.\n"; } } with array_key() <?php $names = array(0 => array( "name" => "Fred", "age" => 20 ), 1 => array( "name" => "George", "age" => 17 ), 2 => array( "name" => "Sarah", "age" => 22 ), 3 => array( "name" => "Fred", "age" => 30 ) ); $name=" Fred"; $array_position = array_keys(array_column($names, "name"), "Fred"); foreach($array_position as $key){ echo $names[$key]["name"] . " is: " . $names[$key]["age"] . " years old.\n"; } OUTPUT: Fred is: 20 years old. Fred is: 30 years old.
What's wrong with a simple foreach loop? // Declare the array $names = array( array( 'name' => 'Fred', 'age' => 20 ), array( 'name' => 'George', 'age' => 17 ), array( 'name' => 'Sarah', 'age' => 22 ), array( 'name' => 'Fred', 'age' => 30 ) ); // Name to search $name = 'Fred'; foreach($names as $index => $data){ if($data['name'] == $name) echo $data['name'] . ' is ' . $data['age'] . ' years old.<br>'; } And the result would be: Fred is 20 years old. Fred is 30 years old.
array_keys() can do this: <?php $names = array( array( 'name' => 'Fred', 'age' => 20 ), array( 'name' => 'George', 'age' => 17 ), array( 'name' => 'Sarah', 'age' => 22 ), array( 'name' => 'Fred', 'age' => 30 ) ); $matchKeys = array_keys( array_column($names, 'name'), 'Fred' ); array_map(function($arrKey) use ($names) { echo $names[$arrKey]['name'] . " is: " . $names[$arrKey]['age'] . " years old.\n"; }, $matchKeys); Result: Fred is: 20 years old. Fred is: 30 years old.
Array( [0] => Array ( [name] => Fred, [age] => 20 ), [1] => Array ( [name] => George, [age] => 17 ), [2] => Array ( [name] => Sarah, [age] => 22 ), [3] => Array ( [name] => Fred, [age] => 30 ) ) $name="Fred"; //loop here for($i =0; i<count($names); $i++){ if($arr[$i] == $name)echo $name . ' is ' . $names[$i] ."years old.<br>"; } //end loop Output: Fred is 20 years old Fred is 30 years old
This can help - $check_name= 'Fred'; // set the name to check $temp= array_filter($names, function($a) use($check_name) { return $a['name'] === $check_name; // return if matches }); // loop through the result foreach($temp as $v) { echo $v['name'] . ' is ' . $v['age'] . ' years old.<br>'; } Output Fred is 20 years old. Fred is 30 years old. Working code Anonymous function & use keyword
I dont understand why you gave space in $name variable $name = " Fred"; Here is your code, $name=" Fred"; function array_search_custom($needle,$haystack) { $temp = []; foreach($haystack as $key=>$value) { if(trim($needle)===trim($value)) { $temp[] =$key; } } return $temp; } $name=" Fred"; $a_names = array_column($names, 'name'); $a_ages = array_column($names, 'age'); $array_position = array_search_custom($name, $a_names); foreach($a_names as $k => $v){ if($array_position && in_array($k, $array_position)){ echo $a_names[$k] . " is: " . $a_ages[$k] . " years old.<br/>"; } } I trimmed your name and wrote custom array search function as per your requirement. Give it a try, it will work.
combine and add data in one array index?
i have a array : Array ( [0] => Array ( [spid] => 20 [name] => Sunny [clientid] => 15 [selectedproduct] => ["190","191"] [memberid] => 637 [partner_id] => 390 [monthly_forecast] => a:2:{i:0;s:151:"[["1","0","0","1","0","0","1","0","1","0","0","0"],["1","0","0","0","1","0","0","0","1","0","1","1"],["1","0","1","0","1","0","1","0","1","0","0","1"]]";i:1;s:151:"[["1","0","1","0","1","0","1","0","1","0","1","0"],["1","0","1","0","1","1","0","1","0","1","0","1"],["1","0","1","0","1","0","1","1","1","0","1","1"]]";} [growth_plan] => {"product":["190","191"],"plans":["8","8"]} [other_palns] => {"product":["190","191"],"plans":["8","8"],"total":["4000","5000"]} [marketing_s_values] => {"190":"2400","191":"7200"} [marketing_s_values_monthly] => {"190":[{"1":"150","2":"150","3":"150","4":"150","5":"150","6":"150","7":"150","8":"150","9":"150","10":"150","11":"150","12":"150"},{"1":"200","2":"200","3":"200","4":"200","5":"200","6":"200","7":"200","8":"200","9":"200","10":"200","11":"200","12":"200"},{"1":"250","2":"250","3":"250","4":"250","5":"250","6":"250","7":"250","8":"250","9":"250","10":"250","11":"250","12":"250"},{"1":"300","2":"300","3":"300","4":"300","5":"300","6":"300","7":"300","8":"300","9":"300","10":"300","11":"300","12":"300"},{"1":"350","2":"350","3":"350","4":"350","5":"350","6":"350","7":"350","8":"350","9":"350","10":"350","11":"350","12":"350"}],"191":[{"1":"500","2":"500","3":"500","4":"500","5":"500","6":"500","7":"500","8":"500","9":"500","10":"500","11":"500","12":"500"},{"1":"600","2":"600","3":"600","4":"600","5":"600","6":"600","7":"600","8":"600","9":"600","10":"600","11":"600","12":"600"},{"1":"700","2":"700","3":"700","4":"700","5":"700","6":"700","7":"700","8":"700","9":"700","10":"700","11":"700","12":"700"},{"1":"800","2":"800","3":"800","4":"800","5":"800","6":"800","7":"800","8":"800","9":"800","10":"800","11":"800","12":"800"},{"1":"900","2":"900","3":"900","4":"900","5":"900","6":"900","7":"900","8":"900","9":"900","10":"900","11":"900","12":"900"}]} ) [1] => Array ( [spid] => 20 [name] => Sunny [clientid] => 15 [selectedproduct] => ["199","210"] [memberid] => 641 [partner_id] => 394 [monthly_forecast] => a:2:{i:0;s:163:"[["10","0","0","0","30","0","0","60","0","0","0","0"],["20","0","0","30","0","0","20","0","0","0","50","0"],["30","0","0","0","20","0","0","30","0","20","0","30"]]";i:1;s:154:"[["20","0","0","0","0","0","0","0","0","0","0","0"],["30","0","0","0","0","0","0","0","0","0","0","0"],["40","0","0","0","0","0","0","0","0","0","0","0"]]";} [growth_plan] => {"product":["199","210"],"plans":["8","8"]} [other_palns] => {"product":["199","210"],"plans":["10","10"],"total":["6000","3000"]} [marketing_s_values] => {"199":"4700","210":"0"} [marketing_s_values_monthly] => {"199":[{"1":"4600","2":"0","3":"0","4":"0","5":"0","6":"0","7":"0","8":"0","9":"0","10":"0","11":"0","12":"0"},{"1":"4700","2":"0","3":"0","4":"0","5":"0","6":"0","7":"0","8":"0","9":"0","10":"0","11":"0","12":"0"},{"1":"4800","2":"0","3":"0","4":"0","5":"0","6":"0","7":"0","8":"0","9":"0","10":"0","11":"0","12":"0"},{"1":"4900","2":"0","3":"0","4":"0","5":"0","6":"0","7":"0","8":"0","9":"0","10":"0","11":"0","12":"0"},{"1":"5000","2":"0","3":"0","4":"0","5":"0","6":"0","7":"0","8":"0","9":"0","10":"0","11":"0","12":"0"}],"210":[{"1":"0","2":"0","3":"0","4":"0","5":"0","6":"0","7":"0","8":"0","9":"0","10":"0","11":"0","12":"0"},{"1":"0","2":"0","3":"0","4":"0","5":"0","6":"0","7":"0","8":"0","9":"0","10":"0","11":"0","12":"0"},{"1":"0","2":"0","3":"0","4":"0","5":"0","6":"0","7":"0","8":"0","9":"0","10":"0","11":"0","12":"0"},{"1":"0","2":"0","3":"0","4":"0","5":"0","6":"0","7":"0","8":"0","9":"0","10":"0","11":"0","12":"0"},{"1":"0","2":"0","3":"0","4":"0","5":"0","6":"0","7":"0","8":"0","9":"0","10":"0","11":"0","12":"0"}]} ) [2] => Array ( [spid] => 20 [name] => Sunny [clientid] => 15 [selectedproduct] => ["190","191","192","193"] [memberid] => 574 [partner_id] => 374 [monthly_forecast] => a:4:{i:0;s:151:"[["1","0","0","1","0","0","1","0","1","0","0","0"],["1","0","0","0","1","0","0","0","1","0","1","1"],["1","0","1","0","1","0","1","0","1","0","0","1"]]";i:1;s:151:"[["1","0","1","0","1","0","1","0","1","0","1","0"],["1","0","1","0","1","1","0","1","0","1","0","1"],["1","0","1","0","1","0","1","1","1","0","1","1"]]";i:2;s:151:"[["1","1","1","0","1","1","1","0","0","0","1","1"],["1","1","1","0","0","1","1","1","1","0","1","1"],["1","1","1","1","0","0","1","1","1","1","1","1"]]";i:3;s:151:"[["1","0","1","0","0","0","1","0","1","0","0","2"],["1","0","0","2","1","0","1","0","1","1","0","1"],["1","0","2","1","1","1","0","1","0","1","1","1"]]";} [growth_plan] => {"product":["190","191","192","193"],"plans":["8","8","9","8"]} [other_palns] => {"product":["190","191","192","193"],"plans":["8","8","8","8"],"total":["4000","5000","1500","36000"]} [marketing_s_values] => {"190":"2400","191":"7200","192":"2400","193":"24000"} [marketing_s_values_monthly] => {"190":[{"1":"150","2":"150","3":"150","4":"150","5":"150","6":"150","7":"150","8":"150","9":"150","10":"150","11":"150","12":"150"},{"1":"200","2":"200","3":"200","4":"200","5":"200","6":"200","7":"200","8":"200","9":"200","10":"200","11":"200","12":"200"},{"1":"250","2":"250","3":"250","4":"250","5":"250","6":"250","7":"250","8":"250","9":"250","10":"250","11":"250","12":"250"},{"1":"300","2":"300","3":"300","4":"300","5":"300","6":"300","7":"300","8":"300","9":"300","10":"300","11":"300","12":"300"},{"1":"350","2":"350","3":"350","4":"350","5":"350","6":"350","7":"350","8":"350","9":"350","10":"350","11":"350","12":"350"}],"191":[{"1":"500","2":"500","3":"500","4":"500","5":"500","6":"500","7":"500","8":"500","9":"500","10":"500","11":"500","12":"500"},{"1":"600","2":"600","3":"600","4":"600","5":"600","6":"600","7":"600","8":"600","9":"600","10":"600","11":"600","12":"600"},{"1":"700","2":"700","3":"700","4":"700","5":"700","6":"700","7":"700","8":"700","9":"700","10":"700","11":"700","12":"700"},{"1":"800","2":"800","3":"800","4":"800","5":"800","6":"800","7":"800","8":"800","9":"800","10":"800","11":"800","12":"800"},{"1":"900","2":"900","3":"900","4":"900","5":"900","6":"900","7":"900","8":"900","9":"900","10":"900","11":"900","12":"900"}],"192":[{"1":"100","2":"100","3":"100","4":"100","5":"100","6":"100","7":"100","8":"100","9":"100","10":"100","11":"100","12":"100"},{"1":"200","2":"200","3":"200","4":"200","5":"200","6":"200","7":"200","8":"200","9":"200","10":"200","11":"200","12":"200"},{"1":"300","2":"300","3":"300","4":"300","5":"300","6":"300","7":"300","8":"300","9":"300","10":"300","11":"300","12":"300"},{"1":"400","2":"400","3":"400","4":"400","5":"400","6":"400","7":"400","8":"400","9":"400","10":"400","11":"400","12":"400"},{"1":"500","2":"500","3":"500","4":"500","5":"500","6":"500","7":"500","8":"500","9":"500","10":"500","11":"500","12":"500"}],"193":[{"1":"1500","2":"1500","3":"1500","4":"1500","5":"1500","6":"1500","7":"1500","8":"1500","9":"1500","10":"1500","11":"1500","12":"1500"},{"1":"2000","2":"2000","3":"2000","4":"2000","5":"2000","6":"2000","7":"2000","8":"2000","9":"2000","10":"2000","11":"2000","12":"2000"},{"1":"2200","2":"2200","3":"2200","4":"2200","5":"2200","6":"2200","7":"2200","8":"2200","9":"2200","10":"2200","11":"2200","12":"2200"},{"1":"2500","2":"2500","3":"2500","4":"2500","5":"2500","6":"2500","7":"2500","8":"2500","9":"2500","10":"2500","11":"2500","12":"2500"},{"1":"2700","2":"2700","3":"2700","4":"2700","5":"2700","6":"2700","7":"2700","8":"2700","9":"2700","10":"2700","11":"2700","12":"2700"}]} ) In this array as you see "spid" is similar to in all the array index.i just want that it will merge all the data in one index array. As you see "selectedproduct" of index 0 and index 2 is similar data like 190 and 191 whenever the "selectedproduct" is similar i just want that there respective "monthly_forecast" values added with each other and merge all the three index values into one but only in the case where there "selectedproduct" is similar only those "monthly_forecast" value added. i tried this code: $new_values = array(); foreach($get_partner_same_forecast as $value) { if(isset($new_values[$value['spid']])) { $temp = $new_values[$value['spid']]; $temp['selectedproduct'] .= ',' . $value['selectedproduct']; $user[] = json_decode($value['selectedproduct'],true); $result = array(); foreach($user as $item) { $result = array_merge($result, $item); } $temp['selectedproduct']=json_encode($result); $temp['partner_acc_name'] .= ',' . $value['partner_acc_name'];//mergepartner name $temp['crm_acc_name'] .= ',' . $value['crm_acc_name']; //merge crmname $temp['memberid'] .= ',' . $value['memberid'];//merge memberid $temp['partner_id'] .= ',' . $value['partner_id'];//merge partnerid $temp['growth_plan'] .= ',' . $value['growth_plan'];//merge growth plan $user1[] = json_decode($value['growth_plan'],true); $product = array(); $plan = array(); foreach($user1 as $k=>$v) { $product = array_merge($product, $v['product']); $plan = array_merge($plan, $v['plans']); $user1[$k]['product'] = $product; $user1[$k]['plans'] = $plan; } $temp['growth_plan']=json_encode($user1[1]); $temp['monthly_forecast'] .= ',' . $value['monthly_forecast'];//merge unserialize monthly data $data1=array(); $data2=array(); $data2=unserialize($value['monthly_forecast']); $data1=unserialize($temp['monthly_forecast']); $combinedData=array(); $combinedData = array($data1, $data2); $monthly_forecast = array(); $monthly_forecast=serialize($combinedData); $temp['monthly_forecast']=$monthly_forecast;//merge monthly $monthly_forecast=unserialize($monthly_forecast); //echo "<pre>"; print_r($monthly_forecast);echo "</pre>"; $new_values[$value['spid']] = $temp; } else { $new_values[$value['spid']] = $value; } } $new_values = array_values($new_values);
Implode multidimensional array with different glue in php
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; }
Implode array giving out error
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;