Have array like this
Array
(
[0] => Array
(
[CategoriesName_1] => Happy Birthday
[CategoriesName_2] => Flowers
[CategoriesName_3] => Fruit baskets
[CategoriesDescription_1] =>
[CategoriesDescription_2] =>
[CategoriesDescription_3] => Fruit baskets descr
[CategoriesUrl_1] => happy-birthday
[CategoriesUrl_2] => flowers
[CategoriesUrl_3] => fruit-baskets
)
)
Want to convert it to array like this (need to get this result)
Array
(
[0] => Array
(
[CategoriesName] => Happy Birthday
[CategoriesDescription] =>
[CategoriesUrl] => happy-birthday
)
[1] => Array
(
[CategoriesName] => Flowers
[CategoriesDescription] =>
[CategoriesUrl] => flowers
)
[2] => Array
(
[CategoriesName] => Fruit baskets
[CategoriesDescription] => Fruit baskets descr
[CategoriesUrl] => fruit-baskets
)
)
The initial (one dimensional array) have keys CategoriesName_1, CategoriesUrl_1, CategoriesDescription_1. For each number (_1, _2, _3) want to put name, url and description together and create separate subarray.
At first created 3 separate arrays
foreach ( $array_with_breadcrumbs[0] as $key_brcr => $val_brcr ) {
if( 'CategoriesUrl_' == substr($key_brcr,0,14) ){
$array_url_brcr[] = array( 'CategoriesUrl' => $val_brcr );
}
if( 'CategoriesName_' == substr($key_brcr,0,15) ){
$array_name_brcr[] = array( 'CategoriesName' => $val_brcr );
}
if( 'CategoriesDescription_' == substr($key_brcr,0,22) ){
$array_description_brcr[] = array( 'CategoriesDescription' => $val_brcr );
}
}//foreach ( $array_with_breadcrumbs[0] as $key_brcr => $val_brcr ) {
Then loop through all three arrays like this
foreach( $array_url_brcr as $i_url => $val_url ){
foreach( $array_name_brcr as $i_name => $val_name ){
foreach( $array_description_brcr as $i_description => $val_description ){
if( $i_url == $i_name ) {
$combined_arr_brcr[] = array(
'CategoriesUrl' => $val_url['CategoriesUrl'],
'CategoriesName' => $val_name['CategoriesName'],
'CategoriesDescription' => $val_description['CategoriesDescription']
);
}
}
}
}
I get nine (3 arrays * 3 loops) subarrays with not expected results. From the results I must write additional code where I take (keep) first, fifth and ninth subarray.
Code appears very long. Is there any better (shorter, simpler) way to get result?
$final_array=array();
for ($i=0; $i < 3; $i++) {
$k=$i+1;
$final_array[$i]=array(
'CategoriesName'=>$array_with_breadcrumbs[0]['CategoriesName_'.$k],
'CategoriesDescription'=>$array_with_breadcrumbs[0]['CategoriesDescription_'.$k],
'CategoriesUrl'=>$array_with_breadcrumbs[0]['CategoriesUrl_'.$k],
);
}
print_r($final_array);
if the number of keys is more than 3 , you can use this
$final_array=array();
$no_of_keys=3; //change the value of number of keys
$vars=array('CategoriesName','CategoriesDescription','CategoriesUrl'); // add variables
for ($i=0; $i < $no_of_keys; $i++) {
$k=$i+1;
$final_array[$i]=array();
foreach ($vars as $var) {
$final_array[$i][$var]=$array_with_breadcrumbs[0][$var."_".$k]
}
}
print_r($final_array);
$source = $array_with_breadcrumbs[0];
$result = [];
for ($i = 1; $i <= 3; $i++)
{
array_push($result,
[
'CategoriesName' => $source['CategoriesName_' . $i],
'CategoriesDescription' => $source['CategoriesDescription_' . $i],
'CategoriesUrl' => $source['CategoriesUrl_' . $i]
]);
}
var_dump($result);
Related
I'm trying to build a tree-map from categories. I have the categories (I have a lot of categories and I want to remove duplicates and show them in a tree-map view with count) and I have the following code:
<?php
$cat = array(
"Sneakers/Men",
"Sneakers/Women",
"Accessories/Jewellery/Men",
"Accessories/Jewellery/Men",
"Accessories/Jewellery/Women",
"Accessories/Jewellery/Men/Bvlgari"
);
$out = [];
foreach ($cat as $str) {
$lookup = &$out;
$parts = explode("/", $str);
foreach ($parts as $part) {
$lookup = &$lookup[$part];
if (!isset($lookup))
$lookup = [];
if ($part == end($parts))
$lookup = is_array($lookup) ? 1 : ++$lookup;
}
}
print_r($out);
OUTPUT:
Array
(
[Sneakers] => Array
(
[Men] => 1
[Women] => 1
)
[Accessories] => Array
(
[Jewellery] => Array
(
[Men] => 3
[Women] => 1
)
)
)
I would like to be:
Array
(
[Sneakers] => Array
(
[Men] => 1
[Women] => 1
)
[Accessories] => Array
(
[Jewellery] => Array
(
[Men] => Array (
[Bvlgari] => 1
)
[Women] => 1
)
)
)
You're losing information with both of those formats and the suggested answer is not going to cut it. You do need recursion and each item needs to hold a count and children.
$cat_paths = [
'Sneakers/Men',
...
];
$cat_counts = $item = [# template of each item
'count' => 0,
'children' => [],
];
foreach ($cat_paths as $cat_path) {
$level = &$cat_counts;# use a reference for recursion
if ($cat_path) {# allow uncategorized to be in root of tree
$cat_path = explode('/', $cat_path);
do {
$cat = array_shift($cat_path);
if (!isset($level['children'][$cat])) {
$level['children'][$cat] = $item;
}
$level = &$level['children'][$cat];# step down into tree
} while ($cat_path);
}
$level['count']++;
}
unset($level);
I have two arrays which the key is a [part id]. The value is record => Qty:Length. I want to be able to check if any of the values under the same part id from the sencond array is greater than the length of the first array. For example the Part id 2099 in the second array has a qty:length of 14:11.25 and that is greater than the 6:3.33 which I want that to return true in PHP. I Have a function to split up the qty and length but after that I am unsure where to go. It returns "Warning: explode() expects parameter 2 to be string," Any Help Appreciated.
Array
(
[2099] => Array
(
[360] => 6:3.33
[362] => 14:8.75
)
[2130] => Array
(
[361] => 4:2.5
)
)
Array
(
[2099] => Array
(
[360] => 12:8.33
[362] => 14:11.25
)
[2130] => Array
(
[361] => 24:3.5
)
)
My PHP:
foreach ($a as $partid=>$qty_length){
$ex_part = explode(":", $qty_length);
}
You can do a nested foreach loop to find the difference
<?php
$array1 = array(2099 => array(360 => "6:3.33",362 => "14:8.75"),2130 => array(361 => "4:2.5"));
$array2 = array(2099 => array(360 => "12:8.33",362 => "14:11.25"),2130 => array(361 => "24:3.5"));
foreach($array1 as $key => $value)
{
foreach ($value as $key1 => $value1) {
// $array1[$key][$key1] get the value of array one curreny key
// $array2[$key][$key1] get the value of array two current key
$one = explode(':',$array1[$key][$key1]); // array one value e.g 360 => "6:3.33"
$two = explode(':',$array2[$key][$key1]); // array two value e.g 360 => "12:8.33"
// do what ever you want here
if($one[0] > $two[0])
{
echo "array one key " . $key1 . " is bigger <br>";
}else{
echo "array two key " . $key1 . " is bigger <br>";
}
}
}
$arr =Array
(
'2099' => Array
(
'360' => '6:3.33',
'362' => '14:8.75'
),
'2130' => Array
(
'361' => '4:2.5'
),
'2131' => Array
(
'362' => '24:3.5'
)
);
$arr1=Array
(
'2099' => Array
(
'360' => '12:8.33',
'362' => '14:11.25'
),
'2130' => Array
(
'361' => '24:3.5'
),
'2131' => Array
(
'362' => '20:3.5'
)
);
foreach ($arr as $partid=>$qty_length){
foreach($qty_length as $key=>$val){
$ex_part = explode(":", $val);
// print_r($ex_part);
$ex_part1 = $arr1[$partid];
$len = sizeof($ex_part1);
foreach( $ex_part1 as $key1=>$val1){
$ex_part1 = explode(":", $arr1[$partid][$key1]);
if($ex_part[0] < $ex_part1[0] && $ex_part[1] < $ex_part1[1]){
$len--;
if($len == 0){
echo $ex_part1[0]."<br>";
}else{
continue;
}
}else if($ex_part[0] >= $ex_part1[0] && $ex_part[1] >= $ex_part1[1]){
$len--;
if($len == 0){
echo $ex_part[0]."else <br>";
}else{
continue;
}
}
}
}
}
you can add more conditions also.
I want to convert multi dimensional array in Php
I'm stuck in logic.. Kindly help
Thanks in advance
Current Produced array :
Array
(
[5316] => Array
(
[0] => Array
(
[PROD1] => color=black
)
[1] => Array
(
[PROD1] => paper=a1
)
[2] => Array
(
[PROD2] => color=metallic_silver
)
[3] => Array
(
[PROD2] => paper=a1
)
)
)
I want to convert this array into this form
Array
(
[5316] => Array
(
[PROD1] => Array
(
color => black
paper => a1
)
[PROD2] => Array
(
color => metallic_silver
paper => a1
)
)
)
If you can't hardcode that key to directly point to it, you can use reset() in this case, then grouped them inside a foreach accordingly. Example:
$array = array(
5316 => array(
array('PROD1' => 'color=black'),
array('PROD1' => 'paper=a1'),
array('PROD2' => 'color=metallic_silver'),
array('PROD2' => 'paper=a1'),
),
);
$grouped = array();
// point it to the first key which gives an array of those values
foreach (reset($array) as $key => $value) {
reset($value); // reset the internal pointer of the sub array
$key = key($value); // this return `PROD1, PROD2`
$grouped[$key][] = current($value); // current gives color=black, the values
}
$array[key($array)] = $grouped; // then reassign
echo '<pre>';
print_r($array);
Sample Output
You can try something like below.
$newArr = [];
$count = count($arr[5316]);
for($i = 0, $j = 1; $i < $count; $i += 2){
$color = explode('=', $arr[5316][$i]['PROD'.$j]);
$paper = explode('=', $arr[5316][$i+1]['PROD'.$j]);
$newArr[5316]['PROD'.$j] = array('color'=>$color[1], 'paper'=>$paper[1]);
$j++;
}
//To show output
print '<pre>';
print_r($newArr);
print '</pre>';
Problem
I have an array which is returned from PHPExcel via the following
<?php
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$excelFile = "excel/1240.xlsx";
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($excelFile);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$arrayData[$worksheet->getTitle()] = $worksheet->toArray();
}
print_r($arrayData);
?>
This returns:
Array
(
[Films] => Array
(
[0] => Array
(
[0] => Name
[1] => Rating
)
[1] => Array
(
[0] => Shawshank Redemption
[1] => 39
)
[2] => Array
(
[0] => A Clockwork Orange
[1] => 39
)
)
[Games] => Array
(
[0] => Array
(
[0] => Name
[1] => Rating
)
[1] => Array
(
[0] => F.E.A.R
[1] => 4
)
[2] => Array
(
[0] => World of Warcraft
[1] => 6
)
)
)
What I would like to have is
Array
(
[Films] => Array
(
[0] => Array
(
[Name] => Shawshank Redemption
[Rating] => 39
)
[1] => Array
(
[Name] => A Clockwork Orange
[Rating] => 39
)
)
[Games] => Array
(
[0] => Array
(
[Name] => F.E.A.R
[Rating] => 4
)
[1] => Array
(
[Name] => World of Warcraft
[Rating] => 6
)
)
)
The arrays names (Films, Games) are taken from the sheet name so the amount can be variable. The first sub-array will always contain the key names e.g. Films[0] and Games[0] and the amount of these can be varible. I (think I) know I will need to do something like below but I'm at a loss.
foreach ($arrayData as $value) {
foreach ($value as $rowKey => $rowValue) {
for ($i=0; $i <count($value) ; $i++) {
# code to add NAME[n] as keys
}
}
}
I have searched extensively here and else where if it is a duplicate I will remove it.
Thanks for any input
Try
$result= array();
foreach($arr as $key=>$value){
$keys = array_slice($value,0,1);
$values = array_slice($value,1);
foreach($values as $val){
$result[$key][] = array_combine($keys[0],$val);
}
}
See demo here
You may use nested array_map calls. Somehow like this:
$result = array_map(
function ($subarr) {
$names = array_shift($subarr);
return array_map(
function ($el) use ($names) {
return array_combine($names, $el);
},
$subarr
);
},
$array
);
Demo
Something like this should work:
$newArray = array();
foreach ($arrayData as $section => $list) {
$newArray[$section] = array();
$count = count($list);
for ($x = 1; $x < $count; $x++) {
$newArray[$section][] = array_combine($list[0], $list[$x]);
}
}
unset($arrayData, $section, $x);
Demo: http://ideone.com/ZmnFMM
Probably a little late answer, but it looks more like your tried solution
//Films,Games // Row Data
foreach ($arrayData as $type => $value)
{
$key1 = $value[0][0]; // Get the Name Key
$key2 = $value[0][1]; // Get the Rating Key
$count = count($value) - 1;
for ($i = 0; $i < $count; $i++)
{
/* Get the values from the i+1 row and put it in the ith row, with a set key */
$arrayData[$type][$i] = array(
$key1 => $value[$i + 1][0],
$key2 => $value[$i + 1][1],
);
}
unset($arrayData[$type][$count]); // Unset the last row since this will be repeated data
}
I think this will do:
foreach($arrayData as $key => $array){
for($i=0; $i<count($array[0]); $i++){
$indexes[$i]=$array[0][$i];
}
for($i=1; $i<count($array); $i++){
for($j=0; $j<count($array[$i]); $j++){
$temp_array[$indexes[$j]]=$array[$i][$j];
}
$new_array[$key][]=$temp_array;
}
}
print_r($new_array);
EDIT: tested and updated the code, works...
Ok so i have a post that looks kind of this
[optional_premium_1] => Array
(
[0] => 61
)
[optional_premium_2] => Array
(
[0] => 55
)
[optional_premium_3] => Array
(
[0] => 55
)
[premium_1] => Array
(
[0] => 33
)
[premium_2] => Array
(
[0] => 36 )
[premium_3] => Array
(
[0] => 88 )
[premium_4] => Array
(
[0] => 51
)
how do i get the highest number out of the that. So for example, the optional "optional_premium_" highest is 3 and the "premium_" optional the highest is 4. How do i find the highest in this $_POST
You could use array_key_exists(), perhaps something like this:
function getHighest($variableNamePrefix, array $arrayToCheck) {
$continue = true;
$highest = 0;
while($continue) {
if (!array_key_exists($variableNamePrefix . "_" . ($highest + 1) , $arrayToCheck)) {
$continue = false;
} else {
highest++;
}
}
//If 0 is returned than nothing was set for $variableNamePrefix
return $highest;
}
$highestOptionalPremium = getHighest('optional_premium', $_POST);
$highestPremium = getHighest('premium', $_POST);
I have 1 question with 2 parts before I answer, and that is why are you using embedded arrays? Your post would be much simpler if you used a standard notation like:
$_POST['form_input_name'] = 'whatever';
unless you are specifically building this post with arrays for some reason. That way you could use the array key as the variable name and the array value normally.
So given:
$arr = array(
"optional_premium_1" => "61"
"optional_premium_2" => "55"
);
you could use
$key = array_keys($arr);
//gets the keys for that array
//then loop through get raw values
foreach($key as $val){
str_replace("optional_premium_", '', $val);
}
//then loop through again to compare each one
$highest = 0;
for each($key as $val){
if ((int)$val > $highest) $highest = (int)$val;
}
that should get you the highest one, but then you have to go back and compare them to do whatever your end plan for it was.
You could also break those into 2 separate arrays and assuming they are added in order just use end() http://php.net/manual/en/function.end.php
Loop through all POST array elements, pick out elements having key names matching "name_number" pattern and save the ones having the largest number portion of the key names. Here is a PHP script which does it:
<?php // test.php 20110428_0900
// Build temporary array to simulate $_POST
$TEMP_POST = array(
"optional_premium_1" => array(61),
"optional_premium_2" => array(55),
"optional_premium_3" => array(55),
"premium_1" => array(33),
"premium_2" => array(36),
"premium_3" => array(88),
"premium_4" => array(51),
);
$names = array(); // Array of POST variable names
// loop through all POST array elements
foreach ($TEMP_POST as $k => $v) {
// Process only elements with names matching "word_number" pattern.
if (preg_match('/^(\w+)_(\d+)$/', $k, $m)) {
$name = $m[1];
$number = (int)$m[2];
if (!isset($names[$name]))
{ // Add new POST var key name to names array
$names[$name] = array(
"name" => $name,
"max_num" => $number,
"key_name" => $k,
"value" => $v,
);
} elseif ($number > $names[$name]['max_num'])
{ // New largest number in key name.
$names[$name] = array(
"name" => $name,
"max_num" => $number,
"key_name" => $k,
"value" => $v,
);
}
}
}
print_r($names);
?>
Here is the output from the script:
Array
(
[optional_premium] => Array
(
[name] => optional_premium
[max_num] => 3
[key_name] => optional_premium_3
[value] => Array
(
[0] => 55
)
)
[premium] => Array
(
[name] => premium
[max_num] => 4
[key_name] => premium_4
[value] => Array
(
[0] => 51
)
)
)
Though ineffective, you could try something like
$largest = 0;
foreach($_POST as $key => $value)
{
$len = strlen("optional_premium_");
$num = substr($key, $len);
if($num > $largest)
$largest = $num;
}
print_r($largest);
The problem being that this will only work for one set of categories. It will most likely give errors throughout the script.
Ideally, you would want to reorganize your post, make each array be something like
[optional_premium_1] => Array
(
[0] => 61
["key"] => 1
)
[optional_premium_2] => Array
(
[0] => 61
["key"] => 2
)
Then just foreach and use $array["key"] to search.