I have an array which stores quantity. I want to convert this into individual array as described below
What i have tried
function expandArray($TICKETTYPE_TEMPARRAY, $readQuantity){
for($i=1; $i<=$readQuantity; $i++){
$TICKETTYPE[] = $TICKETTYPE_TEMPARRAY;
}
}
foreach($TICKETTYPE_TEMPARRAY as $key => $value){
$readQuantity = $value["QUANTITY"];
expandArray($TICKETTYPE_TEMPARRAY, $readQuantity);
}
My array
$myarray = array(
"TICKETPRICE" => "6.0000",
"QUANTITY" => "2",
"COUNTRYID" => "15"
)
Expected output:
[{TICKETPRICE:6.000, QUANTITY:2, COUNTRYID=15},
{TICKETPRICE:6.000, QUANTITY:2, COUNTRYID=15}]
I think you want something like this:
$myarray = array(array(
"TICKETPRICE" => "6.0000",
"QUANTITY" => "2",
"COUNTRYID" => "15"
),
array(
"TICKETPRICE" => "4.0000",
"QUANTITY" => "3",
"COUNTRYID" => "9"
));
$output = array();
foreach ($myarray as $array) {
$output[] = array_fill(0, $array['QUANTITY'], $array);
}
echo json_encode($output);
Output:
[[{"TICKETPRICE":"6.0000","QUANTITY":"2","COUNTRYID":"15"},
{"TICKETPRICE":"6.0000","QUANTITY":"2","COUNTRYID":"15"}
],
[{"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"},
{"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"},
{"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"}
]]
Or if you want a completely flat array:
$output = array();
foreach ($myarray as $array) {
$output = array_merge($output, array_fill(0, $array['QUANTITY'], $array));
}
echo json_encode($output);
Output:
[{"TICKETPRICE":"6.0000","QUANTITY":"2","COUNTRYID":"15"},
{"TICKETPRICE":"6.0000","QUANTITY":"2","COUNTRYID":"15"}
{"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"},
{"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"},
{"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"}
]
Demo on 3v4l.org
Simply array_fill and json_encode may help you.
<?php
$myarray = array(
"TICKETPRICE" => "6.0000",
"QUANTITY" => "2",
"COUNTRYID" => "15"
);
$myarray = json_encode(array_fill(0, $myarray['QUANTITY'], $myarray));
print '<pre>';
print_r($myarray);
?>
Related
im having troubles with sorting array with nested array etc. Array looks like this:
$array = array(
"item" => array(
"childs" => array(
01 => array(
"name" => "Min",
"content" => "CC",
"number" => "111"
),
02 => array(
"name" => "Min",
"content" => "BB",
"number" => "101"
),
03 => array(
"name" => "Min",
"content" => "AA",
"number" => "115"
),
04 => array(
"name" => "Min",
"content" => "BB",
"number" => "100"
),
)
),
);
I want to sort that array (childs to be specific) by CONTENT and NUMBER. Here's my code:
foreach ($array as $item) {
foreach($item as $childs) {
$row = array();
$number = array();
foreach($childs as $child) {
$row[] = $child["row"];
$number[] = $child["number"];
}
array_multisort($number, SORT_ASC, SORT_NUMERIC, $row, SORT_ASC, $childs);
};
};
But it does not seem to work. I got no error but the array is not sorted. Can somebody give me a hand?
I guess root cause is: "when you loop array. Item in array is not reference variable (you have sorted in another array)".
You can try by passing reference variable.
foreach ($array as &$item) {
foreach($item as &$childs) {
$row = array();
$number = array();
foreach($childs as $child) {
$row[] = $child["row"];
$number[] = $child["number"];
}
array_multisort($number, SORT_ASC, SORT_NUMERIC, $row, SORT_ASC, $childs);
};
};
I have an array with indexes like
$array = array(
"first_name" => "test",
"last_name" => "testsurename"
);
I need to convert it to:
$array = array(
"0" => array("first_name" => "test"),
"1" => array("last_name" => "testsurename")
);
try this,
$array = array("first_name"=>"test","last_name"=>"testsurename");
$newarray = array();
foreach($array as $key=> $val)
{
$newarray[][$key] = $val;
}
print_r($newarray);
OUTPUT :
$array = array(
"0" => array("first_name" => "test"),
"1" => array("last_name" => "testsurename")
);
DEMO
Another way is to use array_walk, but basically it's all the same.
$array = array("first_name"=>"test","last_name"=>"testsurename");
$result = array();
array_walk($array,
function(&$item, $key, $target) { $target[] = array($key => $item); },
&$result);
You can try
<?php
$array = array("first_name"=>"test","last_name"=>"testsurename");
$final_array = [];
foreach ($array as $key => $value) {
array_push($final_array, [$key => $value]);
}
print_r($final_array);
Output
Array ( [0] => Array ( [first_name] => test ) [1] => Array ( [last_name] => testsurename ) )
$inputArray = [
"first_name" => "test",
"last_name" => "testsurename"
];
$outputArray = array_reduce(array_keys($inputArray), function($carry, $key) use ($inputArray) {
$carry[][$key] = $array[$key];
return $carry;
}, []);
/**
result will be for $outputArray
[
["first_name" => "test"],
["last_name" => "testsurename"]
];
**/
I have tried to loop this array but I still get error
I have an array like this:
1 => ["name"=>"A", "related"=>[
["signal"=>"A1", "color"=>"green"],
["signal"=>"A2", "color"=>"lime"],
["signal"=>"A3","color"=>"yellowGreen"]
]]
2 => ["name"=>"B", "related"=>[
["signal"=>"B1", "color"=>"Red"],
["signal"=>"B2", "color"=>"Pink"]
]]
How to display as - A : Green, lime, yellowGreeb
- B : Red, Pink
This is my code that I've tried to display as above format
foreach($arr as $key => $value){
echo $value["name"];
foreach($value["related"] as $k){
echo $k["color"] . ",";
}
}
It throw error this array dont has $value["related"] index. But It can echo the $value["name"]???
Thank you!
Find the solution as below:
$array = [1 => [
"name" => "A",
"related" => [
["signal" => "A1", "color" => "green"],
["signal" => "A2", "color" => "lime"],
["signal" => "A3", "color" => "yellowGreen"]
]
],
2 => ["name" => "B", "related" => [
["signal" => "B1", "color" => "Red"],
["signal" => "B2", "color" => "Pink"]
]]
];
foreach ($array as $ar) {
$new_arr = array_column($ar['related'], 'color');
$required_string = implode(', ', $new_arr);
echo $ar['name'].' : ' .$required_string;
echo "<br />";
}
For PHP Version < 5.5 you can use below solution:
foreach ($array as $ar) {
$new_arr = array_map(function ($value) {
return $value['color'];
}, $ar['related']);
$required_string = implode(', ', $new_arr);
echo $ar['name'].' : ' .$required_string;
echo "<br />";
}
you can found more detail about foreach loop at http://php.net/manual/en/control-structures.foreach.php
I have two arrays that look like this:
(this one is ordered by value_max)
$max_values = [
["name" => "john", "id" => 5, "value_max" => 500],
["name" => "john", "id" => 3, "value_max" => 200],
...
];
$min_values = [
["name" => "john", "id" => 5, "value_min" => 100],
["name" => "john", "id" => 3, "value_min" => 150],
...
];
And I need to have a final array like this:
(This one stills need to be ordered by value_max, so I assume I could just overwrite the first array with the calculations done with the second)
$max_and_difference_values = [
["name" => "john", "id" => 5, "value_max" => 500, "difference_value" => 400],
["name" => "john", "id" => 3, "value_max" => 200, "difference_value" => 50 ],
...
];
My question is pretty straight: What is the best/effective way to run through both first arrays and build the last one. Assuming that the size of the arrays can be of around 150 elements.
To avoid looping through all arrays repeatedly, index one array by the field you want to merge on, i.e. the 'id' key:
$second = array_combine(array_map(function ($i) { return $i['id']; }, $second_array), $second_array);
Then looping through the other and comparing the values is pretty easy:
$third = array();
foreach ($first_array as $i) {
$third[] = $i + array('difference_value' => $i['value_max'] - $second[$i['id']]['value_min']);
}
If it's guaranteed that both arrays will have exactly matching keys, you don't even need the first step and just go by already existing keys.
This will sort your array. So you can sort the second array.
<?php
$min_values = array(
array("name" => "john", "id" => 5, "value_min" => 100),
array("name" => "john", "id" => 3, "value_min" => 150),
);
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
aasort($min_values,"id");
echo "<pre>";
print_r($min_values);
echo "</pre>";
?>
And then you can use the logic what Alessandro Minoccheri mentioned.
$arr = array();
for ($i=0; $i<count($first_array);$i++){
$arr['name'] = $first_array[$i]['name'];
$arr['id'] = $first_array[$i]['id'];
$arr['value_max'] = $first_array[$i]['value_max'];
$arr['difference_value'] = $first_array[$i]['value_max']-$second[$i['id']]['value_max'] ;
}
As you have not shared how the second array with the minimum values is ordered (in itself and relative to the maximum values array), I'd say, index the minimum values by the id entry and then do the calculation in a second iteration. It should be fast enough, 150 elements is just "nothing":
$max_values = [
["name" => "john", "id" => 5, "value_max" => 500],
["name" => "john", "id" => 3, "value_max" => 200],
];
$min_values = [
["name" => "john", "id" => 5, "value_min" => 100],
["name" => "john", "id" => 3, "value_min" => 150],
];
$min_values_by_id = [];
foreach($min_values as $min) {
$min_values_by_id[$min['id']] = $min['value_min'];
}
$max_and_difference_values = $max_values;
foreach($max_and_difference_values as &$entry)
{
$entry['difference_value'] = $entry['value_max'] - $min_values_by_id[$entry['id']];
}
unset($entry);
print_r($max_and_difference_values);
This is just a straight forward example, nothing fancy. Demo
the following works for me. I'm not a PHP expert though, i.e. I'm not so familiar with cloning (note the empty clone array). Note that it only copies existing properties (if one array does contain a min_value and another does only contain a some other key)
In essence
function convertArr( $arr ) {
// Easy referencing without having to search through the arrays more than once for a matching id
$new_arr = array();
foreach( $arr as $array ) {
$new_arr[ $array['id'] ] = cloneArr( $array );
}
return $new_arr;
}
function merge( $arr1, $arr2 ) {
$convertedArr1 = convertArr( $arr1 );
$convertedArr2 = convertArr( $arr2 );
$arr = array();
// Based on the ordered array
foreach( $convertedArr1 as $array ) {
$id = $array['id'];
$tempArr = array();
foreach( $convertedArr1[ $id ] as $k => $v ) {
$tempArr[ $k ] = $v;
}
foreach( $convertedArr2[ $id ] as $k => $v ) {
$tempArr[ $k ] = $v;
}
array_push( $arr, $tempArr );
}
return $arr;
}
Full example:
<?php
//$arr1 = [ ["name" => "john", "id" => 5, "value_max" => 500], ["name" => "john", "id" => 3, "value_max" => 200] ];
//$arr2 = [ ["name" => "john", "id" => 5, "value_min" => 100], ["name" => "john", "id" => 3, "value_min" => 150] ];
$arr1 = array(
array( "name" => "john", "id" => 5, "value_max" => 500 ),
array( "name" => "john", "id" => 3, "value_max" => 200 )
);
$arr2 = array(
array( "name" => "john", "id" => 5, "value_min" => 100 ),
array( "name" => "john", "id" => 3, "value_min" => 150 )
);
function neatPrint( $arr ) {
echo "<pre>";
print_r( $arr );
echo "</pre>";
}
echo "<h2>Before</h2>";
neatPrint( $arr1 );
neatPrint( $arr2 );
echo "<hr/>";
function cloneArr( $old ) {
// I dunno how to properly clone
return $old;
}
function convertArr( $arr ) {
// Easy referencing without having to search through the arrays more than once for a matching id
$new_arr = array();
foreach( $arr as $array ) {
$new_arr[ $array['id'] ] = cloneArr( $array );
}
return $new_arr;
}
function merge( $arr1, $arr2 ) {
$convertedArr1 = convertArr( $arr1 );
$convertedArr2 = convertArr( $arr2 );
$arr = array();
// Based on the ordered array
foreach( $convertedArr1 as $array ) {
$id = $array['id'];
$tempArr = array();
neatPrint( $convertedArr1[ $id ] );
neatPrint( $convertedArr2[ $id ] );
foreach( $convertedArr1[ $id ] as $k => $v ) {
$tempArr[ $k ] = $v;
}
foreach( $convertedArr2[ $id ] as $k => $v ) {
$tempArr[ $k ] = $v;
}
array_push( $arr, $tempArr );
}
echo "<h2>Result</h2>";
return $arr;
}
echo "<h2>Loopthrough</h2>";
neatPrint( merge( $arr1, $arr2 ) );
?>
Let me know what you think :-)
if the element are in order try this code:
$arr = array();
for ($i=0; $i<count($first_array);$i++){
$arr['name'] = $first_array[$i]['name'];
$arr['id'] = $first_array[$i]['id'];
$arr['value_max'] = $first_array[$i]['value_max'];
$arr['difference_value'] = $first_array[$i]['value_max']-$second[$i['id']]['value_max'] ;
}
I have an array like this:
$_SESSION['food'] = array(
// ARRAY 1
array(
"name" => "apple",
"shape" => "round",
"color" => "red"
),
// ARRAY 2
array(
"name" => "banana",
"shape" => "long",
"color" => "yellow"
)
);
I want to search through all keys in all child arrays and delete the entire child array if the search term is found.
So, basically:
If searching for "long", the entire Array 2 is removed.
If searching for "apple", the entire Array 1 is removed.
How would I accomplish this?
Thanks!
This should do the trick:
foreach ($array as $key => $value) {
foreach ($value as $child_value) {
if ($child_value == $search_term) {
unset($array[$key]);
continue 2;
}
}
}
Depending on how many dimensions you have, you can use array_search.
I haven't tested the following, but it should work:
$unset = array_search('apple', $_SESSION['food']);
unset($_SESSION['food'][$unset]);
Here you go:
<?php
function deleteObjWithProperty($search,$arr)
{
foreach ($arr as &$val)
{
if (array_search($search,$val)!==false)
{
unlink($val);
}
}
return $arr;
}
?>
$_SESSION['food'] = array(
// ARRAY 1
array(
"name" => "apple",
"shape" => "round",
"color" => "red"
),
// ARRAY 2
array(
"name" => "banana",
"shape" => "long",
"color" => "yellow"
)
);
echo '<pre>'.print_r($_SESSION['food']).'</pre>';
$arr_food = array();
$search_term = 'apple';
foreach($_SESSION['food'] AS $arr) {
if($arr['name'] == $search_term) {
unset($arr);
}
$arr_food[] = $arr;
}
$_SESSION['food'] = $arr_food;
echo '<pre>'.print_r($_SESSION['food']).'</pre>';