How to get deep key in array php? - php

If a have an array:
Array
(
[1-title1] => Array
(
[0] => title = title erer
[1] => 1-title1
[2] => content = content 1
)
[2-title2] => Array
(
[0] => title = title dffgfghfdg
[1] => 2-title2
[2] => content = content 2
)
and I want to get array:
Array
(
[1-title1] => Array
(
[title] =>title erer
[1] =>title1
[content] =>content 1
)
[2-title2] => Array
(
[title] =>title dffgfghfdg
[2] => title2
[content] =>content 2
)
What should I do?

A solution without references and no implicit key names.
foreach ($array as $key => $innerArray) {
foreach ($innerArray as $innerKey => $value) {
if (false !== strpos($value, ' = ')) {
unset($array[$key][$innerKey]);
list($innerKey, $value) = explode(' = ', $value, 2);
$array[$key][$innerKey] = $value;
}
}
}

foreach($array as &$title){
$newTitle = array();
$titleName = explode(' = ', $title[0] , 2);
$newTitle['title'] = end($titleName);
$titleNum = explode('-', $title[1] , 2);
$newTitle[$titleNum[0]] = $titleNum[1];
$titleContent = explode(' = ', $title[2] , 2);
$newTitle['content'] = end($titleContent);
$title = $newTitle;
}

try this
foreach($array as $ky=>$val) {
echo $ky;
var_dump(array_keys($val));
}

Related

Array keep on repeating in foreach

I have an array holding string in it's values, I am finding underscore in each value breaking it and inserting it into new array, It's doing all right but only for first array in second array it repeats first array also.
For Example
$someArraVal[] = 'abc_xyz__vr1_vr2';
$someArraVal[] = 'emf_ccc__vr2_vr3';
First I am getting everything after double underscore then exploding them with underscore and trying to have array like below
Array
(
[0] => Array
(
[0] => vr1
[1] => vr2
)
[1] => Array
(
[2] => vr3
[3] => vr4
)
)
but I am getting
Array
(
[0] => Array
(
[0] => vr1
[1] => vr2
)
[1] => Array
(
[0] => vr1
[1] => vr2
[2] => vr3
[3] => vr4
)
)
CODE
$someArraVal[] = 'abc_xyz__vr1_vr2';
$someArraVal[] = 'emf_ccc__vr3_vr4';
$arr1 = [];
$arr2 = [];
$xmx = [];
foreach ($someArraVal as $key => $value) {
$afterunderscore = substr($value, strpos($value, "__") + 1);
// $addPipe = str_replace("_","|",$afterunderscore);
$abc = substr($afterunderscore, 1);
$arr1 = explode('_',$abc);
foreach ($arr1 as $k => $v) {
$arr2[] = $v;
}
$xmx[] = $arr2;
}
printR($xmx);
You need to empty the array $arr2 at the start of foreach loop.
.
.
.
foreach ($someArraVal as $key => $value) {
$arr2 = []; //Empty the $arr2 at begining of the loop
.
.
.
}
You never reset $arr2 so you append more data each iteration.
You can add $arr2 = [] right after the foreach.
Better solution will be to do:
foreach ($someArraVal as $key => $value) {
$afterunderscore = substr($value, strpos($value, "__") + 1);
$xmx[] = explode('_',substr($afterunderscore, 1));
}
Live example: 3v4l
Second array keeps repeating because you are looping inside the array which will take all the values.
<?php
$someArraVal[] = 'abc_xyz__vr1_vr2';
$someArraVal[] = 'emf_ccc__vr3_vr4';
$arr1 = [];
foreach ($someArraVal as $key => $value) {
$afterunderscore = substr($value, strpos($value, "__") + 1);
$abc = substr($afterunderscore, 1);
$arr1[] = explode('_',$abc);
}
echo '<pre>';
print_r($arr1);
echo '</pre>';
Please check : https://prnt.sc/oitez2
Another technique using a single iterated function call...
Code: (Demo)
$someArraVal[] = 'abc_xyz__vr1_vr2';
$someArraVal[] = 'emf_ccc__vr2_vr3';
foreach ($someArraVal as $value) {
$xmx[] = preg_split('~(?:[^_]+_)*_~', $value, 0, PREG_SPLIT_NO_EMPTY);
}
print_r($xmx);
Output:
Array
(
[0] => Array
(
[0] => vr1
[1] => vr2
)
[1] => Array
(
[0] => vr2
[1] => vr3
)
)
The pattern consumes the undesired substrings and treats them as delimiters. This leaves you with only the substrings that you want.
If the idea of regex scares you, here's a non-regex solution with just two calls per iteration:
foreach ($someArraVal as $value) {
$xmx[] = array_slice(explode('_', $value, 5), -2);
}
// same result array

Combine two arrays together

I have an array that looks like this:
array
(
[name] => name
[description] => description here
[first] => Array
(
[0] => weight
[1] => height
)
[second] => Array
(
[0] => 20 kg
[1] => 50 cm
)
[company_id] => 1
[category_id] => 7
)
what function will allow me to combine these into something that looks like the following?
array
(
[together]
(
[0] => weight 20kg
[1] => height 50cm
)
)
Update
For that current array you need to use the loop.
$first = $second = array();
foreach($yourArray as $key => $array) {
if(in_array($key, array('first', 'second')) {
$first[] = $array[0];
$second[] = $array[1];
}
}
$final['together'] = array($first, $second);
According to the first array
You can try this -
$new = array(
'together' => array(
implode(' ', array_column($yourArray, 0)), // This would take out all the values in the sub arrays with index 0 and implode them with a blank space
implode(' ', array_column($yourArray, 1)), // Same as above with index 1
)
);
array_column is supported PHP >= 5.5
Or you can try -
$first = $second = array();
foreach($yourArray as $array) {
$first[] = $array[0];
$second[] = $array[1];
}
$final['together'] = array($first, $second);
you also can try array_map as below
function merge($first,$second)
{
return $first ." ".$second;
}
$combine = array_map('merge', $yourArray[0],$yourArray[1]);

Calculating average value for array with PHP?

My head is exploding with this. I can't seem to create a working solution.
I have a file in this format:
99895|35378|0.01
99895|813|-0.97
99895|771|0.29
442|833|-1.06
442|485|-0.61
442|367|-0.14
442|478|0.77
442|947|-0.07
7977|987|0.76
7977|819|0.37
7977|819|0.36
7977|653|1.16
7977|1653|1.15
I want to calculate average values from third column for each id from the first column.
This seems so easy but I can't get this to work. How do you get averages for any said id from first column?
EDIT:
Some sample code I've written before:
$file = file_get_contents("results.txt");
$file = explode("
", $file);
$howMany = count($file);
for($a = 0;$a<$howMany;$a++)
{
$row = explode("|", $file[$a]);
$id = $row[0];
$howManyAlready = count($bigTable[$id]);
$bigTable[$id][$howManyAlready] = $row[2];
}
I've added the code. So far it gets the results into an array ( with offset corresponding to its id ) But I am having trouble with how to get those results and calculate average for each id and then present it on the screen.
Something like this should definitely work..
<?php
$arr=array();
$arrv=array_filter(file('myfile.txt'),'strlen');
foreach($arrv as $v)
{
array_push($arr,#array_pop(explode('|',$v)));
}
echo $avg = array_sum($arr)/count($arr);
You can try doing this :
$file = file_get_contents("results.txt");
$file = explode("
", $file);
$valuesPerID = Array();
foreach($file as $row)
{
$row_array = explode("|", $row);
$id = $row_array[0];
if(!array_key_exists($id, $valuesPerID))
{
$valuesPerID[$id] = Array();
}
$valuesPerID[$id][] = $row_array[2];
}
Now in the $valuesPerID array, you'll have all your ID as keys, and for each ID, all the values associated with the said ID. They you can easily calculate the average of these values !
You can use array mapping to assign value and id.
For example (assume that you have handled the text):
<?php
$data = array("99895|35378|0.01",
"99895|813|-0.97",
"99895|771|0.29",
"442|833|-1.06",
"442|485|-0.61",
"442|367|-0.14",
"442|478|0.77",
"442|947|-0.07",
"7977|987|0.76",
"7977|819|0.37",
"7977|819|0.36",
"7977|653|1.16",
"7977|1653|1.15");
$bucket = array();
$count = array();
foreach($data as $line) {
list($id, $what_s_this, $number) = explode("|", $line);
$count[$id]++;
$bucket[$id]+= (float)$number;
}
foreach($bucket as $id => $sum) {
echo "id:". $id. ", average". $sum / $count[$id]. "\n";
}
This should put you on the right track.
<?php
$values = array();
foreach (file('file.txt') as $line) {
list($id, $thingymabob, $value) = explode('|', $line);
if ( ! array_key_exists($id, $values)) {
$values[ $id ] = array();
}
array_push($values[ $id ], $value);
}
foreach ($values as $id => $value) {
printf(
"%d has an average of %f\n",
$id,
array_sum($value) / count($value)
);
}
Here some something I've just written.
In my example it takes it from a string.
<?php
$test1 = "";
$test2 = "";
$count1 = 0;
$count2 = 0;
$string = "99895|35378|0.01
99895|813|-0.97
99895|771|0.29
442|833|-1.06
442|485|-0.61
442|367|-0.14
442|478|0.77
442|947|-0.07
7977|987|0.76
7977|819|0.37
7977|819|0.36
7977|653|1.16
7977|1653|1.15";
$d = explode("\n", $string);
foreach ($d as $k => $v)
{
$d2 = explode("|", $v);
if ($d2[0] == '99895'){
$count1++;
$test1 += $d2[2];
}
if ($d2[0] == '442'){
$count2++;
$test2 += $d2[2];
}
}
$result1 = $test1 / $count1;
$result2 = $test2 / $count2;
echo $result1. " <br> ". $result2;
I don't know how well this will work as I don't know if the values are set or not.
If You try below code
<?php
$file_content = array();
$handle = fopen("test.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line read.
$line_ex = explode("|",$line);
array_push($file_content,$line_ex);
}
} else {
// error opening the file.
}
echo "<pre>";
print_r($file_content);
echo "<pre>";
?>
then You will get below output
Array
(
[0] => Array
(
[0] => 99895
[1] => 35378
[2] => 0.01
)
[1] => Array
(
[0] => 99895
[1] => 813
[2] => -0.97
)
[2] => Array
(
[0] => 99895
[1] => 771
[2] => 0.29
)
[3] => Array
(
[0] => 442
[1] => 833
[2] => -1.06
)
[4] => Array
(
[0] => 442
[1] => 485
[2] => -0.61
)
[5] => Array
(
[0] => 442
[1] => 367
[2] => -0.14
)
[6] => Array
(
[0] => 442
[1] => 478
[2] => 0.77
)
[7] => Array
(
[0] => 442
[1] => 947
[2] => -0.07
)
[8] => Array
(
[0] => 7977
[1] => 987
[2] => 0.76
)
[9] => Array
(
[0] => 7977
[1] => 819
[2] => 0.37
)
[10] => Array
(
[0] => 7977
[1] => 819
[2] => 0.36
)
[11] => Array
(
[0] => 7977
[1] => 653
[2] => 1.16
)
[12] => Array
(
[0] => 7977
[1] => 1653
[2] => 1.15
)
)
For determining average value from third column of corresponding first column - I am researching on it. When I will be done I'll put it here.
Try this:
$filename = 'results.txt';
$result = $counter = $values = array();
$file = fopen($filename, 'r') or die("Couldn't open $filename");
while ($line = fgets($file)) {
$content = explode('|', $line);
if (empty($content[0]) or empty($content[2]))
continue;
$values[$content[0]][] = (float) $content[2];
++$counter[$content[0]];
}
foreach ($values as $key => $value) {
$result[$key] = array_sum($value) / $counter[$key];
}
fclose($file);

How to get the value from serialized array by using preg_match in php

I need to get the value from the serialized array by matching the index value.My unserialized array value is like
Array ( [info1] => test service [price_total1] => 10
[info2] => test servicing [price_total2] => 5 )
I need to display array like
Array ( [service_1] => Array ([info]=>test service [price_total] => 10 )
[service_2] => Array ([info]=>test servicing [price_total] => 5 ))
buy i get the result like the below one
Array ( [service_1] => Array ( [price_total] => 10 )
[service_2] => Array ( [price_total] => 5 ) )
my coding is
public function getServices($serviceinfo) {
$n = 1;
$m = 1;
$matches = array();
$services = array();
print_r($serviceinfo);
if ($serviceinfo) {
foreach ($serviceinfo as $key => $value) {
if (preg_match('/info(\d+)$/', $key, $matches)) {
print_r($match);
$artkey = 'service_' . $n;
$services[$artkey] = array();
$services[$artkey]['info'] = $serviceinfo['info' . $matches[1]];
$n++;
}
if ($value > 0 && preg_match('/price_total(\d+)$/', $key, $matches)) {
print_r($matches);
$artkey = 'service_' . $m;
$services[$artkey] = array();
$services[$artkey]['price_total'] = $serviceinfo['price_total' . $matches[1]];
$m++;
}
}
}
if (empty($services)) {
$services['service_1'] = array();
$services['service_1']['info'] = '';
$services['service_1']['price_total'] = '';
return $services;
}
return $services;
}
I try to print the matches it will give the result as
Array ( [0] => info1 [1] => 1 ) Array ( [0] => price_total1 [1] => 1 )
Array ( [0] => info2 [1] => 2 ) Array ( [0] => price_total2 [1] => 2 )
Thanks in advance.
try this. shorted version and don't use preg_match
function getServices($serviceinfo) {
$services = array();
if (is_array($serviceinfo) && !empty($serviceinfo)) {
foreach ($serviceinfo as $key => $value) {
if(strpos($key, 'info') === 0){
$services['service_'.substr($key, 4)]['info']=$value;
}elseif (strpos($key, 'price_total') === 0){
$services['service_'.substr($key, 11)]['price_total']=$value;
}
}
}
return $services;
}
$data = array('info1'=>'test service','price_total1'=>10,'info2'=>'test servicing','price_total2'=>5);
$service = getServices($data);
print_r($service);

Deleting redundant data inside an array

I have a problem, I have this result below and I want to remove the same timestamp.
Sample Result:
Array
(
[0] => [1341100800000, 0]
[1] => [1341100800000,85]
[2] => [1343779200000,54]
[3] => [1343779200000, 0]
)
Expecting Output
Array
(
[0] => [1341100800000,85]
[1] => [1343779200000,54]
)
I'm thinking of using explode then substr function to get the value. Here is what I came up so far..
$explode = array();
foreach($string_format as $key => $value) {
$explode[] = explode(',', substr($value, 1));
if((isset($explode[0]) && $explode[0][0] == $explode[1][0])) {
unset($explode[0]);
}
//print_r($explode);
}
wouldn't this be a good use of http://us2.php.net/manual/en/function.array-unique.php
Script:
foreach($string_format as $key => $value) {
$explode = explode(',', $value);
$unique[$explode[0]] = $value;
}
Input:
$string_format = array('0' => '1341100800000, 0',
'1' => '1341100800000,85',
'2' => '1343779200000,54',
'3' => '1343779200000, 0');
Output:
$unique =
Array
(
[1341100800000] => 1341100800000,85
[1343779200000] => 1343779200000, 0
)
This should work fine :)
$explode = array();
$timestmp = array();
foreach($string_format as $key => $value) {
$explode[$key] = explode(',', substr($value, 1));
if( in_array( $explode[$key][0], $timestmp)) {
unset ($explode[$key]);
} else {
$timestmp[]= $explode[$key][0];
}
}

Categories