PHP Insert Into MultiDimensional Array - php

I have a functon that is passed an array of url's. I am extracting data from each webpage and then assigning each piece of data to an array. Here's my function:
function getitems ($urls) {
$iteminfo = array();
foreach($urls as $link) {
$circdl = my_curl($link);
$circqp = htmlqp($circdl,'body');
$itemtitle = $circqp->branch()->find('div[class="col-item"]')->children('img')->attr('title');
$itemlink = $circqp->branch()->find('div[class="col-item"]')->children('img')->attr('src');
$itemdesc = $circqp->branch()->find('div[class="col-item"]')->children('img')->attr('alt');
$iteminfo[][] = $itemtitle;
//$iteminfo[$itemtitle][] = $itemlink;
//$iteminfo[$itemtitle][] = $itemdesc;
}
return $iteminfo;
}
I want the array to look like this:
Array ( [0] => Array ( [0] => title [1] => link [2] => desc ) [1] => Array ( [0] => title [1] => link [2] => desc ) [2] => Array ( [0] => title [1] => link [2] => desc ) )
But I can't wrap my head around how to additional fields to the sub-arrays.

try something like this
function getitems ($urls) {
$iteminfo = array();
$i = 0;
foreach($urls as $link) {
$circdl = my_curl($link);
$circqp = htmlqp($circdl,'body');
$itemtitle = $circqp->branch()->find('div[class="col-item"]')->children('img')->attr('title');
$itemlink = $circqp->branch()->find('div[class="col-item"]')->children('img')->attr('src');
$itemdesc = $circqp->branch()->find('div[class="col-item"]')->children('img')->attr('alt');
$iteminfo[$i][] = $itemtitle;
$iteminfo[$i][] = $itemlink;
$iteminfo[$i][] = $itemdesc;
$i++;
}
return $iteminfo;
}
Everything is ok, you just have to assign index to each of your rows.

If i understand you correctly...
$iteminfo[] = array($itemtitle, $itemlink, $itemdesc);

function getitems ($urls) {
$iteminfo = array();
foreach($urls as $link) {
$subInfo = array();
$circdl = my_curl($link);
$circqp = htmlqp($circdl,'body');
$subInfo[] = $circqp->branch()->find('div[class="col-item"]')->children('img')->attr('title');
$subInfo[] = $circqp->branch()->find('div[class="col-item"]')->children('img')->attr('src');
$subInfo[] = $circqp->branch()->find('div[class="col-item"]')->children('img')->attr('alt');
$iteminfo[] = $subInfo;
}
return $iteminfo;
}

You could easily replace
$iteminfo[][] = $itemtitle;
//$iteminfo[$itemtitle][] = $itemlink;
//$iteminfo[$itemtitle][] = $itemdesc;
with
$iteminfo = array($itemtitle, $itemlink, $itemdesc);
You can do this because the syntax
$array = $element; // where $array = array();
is just another way to add element to an array in PHP and $element can be an array() as well.

Related

Combine same indexes of array

I have an array which as dynamic nested indexes in e.g. I am just using 2 nested indexes.
Array
(
[0] => Array
(
[0] => 41373
[1] => 41371
[2] => 41369
[3] => 41370
)
[1] => Array
(
[0] => 41378
[1] => 41377
[2] => 41376
[3] => 41375
)
)
Now I want to create a single array like below. This will have 1st index of first array then 1st index of 2nd array, 2nd index of first array then 2nd index of 2nd array, and so on. See below
array(
[0] =>41373
[1] => 41378
[2] => 41371
[3] => 41377
[4] => 41369
[5] => 41376
[6] => 41370
[7] => 41375
)
You can do something like this:
$results = [];
$array = [[1,2,3,4], [1,2,3,4], [1,2,3,4]];
$count = 1;
$size = count($array)-1;
foreach ($array[0] as $key => $value)
{
$results[] = $value;
while($count <= $size)
{
$results[] = $array[$count][$key];
$count++;
}
$count = 1;
}
I think you need something like this:
function dd(array $arrays): array
{
$bufferArray = [];
foreach($arrays as $array) {
$bufferArray = array_merge_recursive($bufferArray, $array);
}
return $bufferArray;
}
$array1 = ['41373','41371','41369','41370'];
$array2 = ['41378','41377', '41376', '41375'];
$return = array();
$count = count($array1)+count($array2);
for($i=0;$i<($count);$i++){
if($i%2==1){
array_push($return, array_shift($array1));
}
else {
array_push($return, array_shift($array2));
}
}
print_r($return);
first count the arrays in the given array, then count the elements in the first array, than loop over that. All arrays should have the same length, or the first one should be the longest.
$laArray = [
['41373','41371','41369','41370'],
['41378', '41377', '41376', '41375'],
['43378', '43377', '43376', '43375'],
];
$lnNested = count($laArray);
$lnElements = count($laArray[0]);
$laResult = [];
for($lnOuter = 0;$lnOuter < $lnElements; $lnOuter++) {
for($lnInner = 0; $lnInner < $lnNested; $lnInner++) {
if(isset($laArray[$lnInner][$lnOuter])) {
$laResult[] = $laArray[$lnInner][$lnOuter];
}
}
}
this would be the simplest solution:
$firstarr = ['41373','41371','41369','41370'];
$secondarr = ['41378','41377','41376','41375'];
$allcounged = count($firstarr)+count($secondarr);
$dividedintotwo = $allcounged/2;
$i = 0;
while ($i<$dividedintotwo) {
echo $firstarr[$i]."<br>";
echo $secondarr[$i]."<br>";
$i++;
}

Passed multidimensional array to view in codeigniter

I'm trying to create foreach statement using multidimensional array.
Controller:
function index()
{
$index1 = 0;
$index2 = 0;
$index3 = 0;
$index4 = 0;
$result1 = $this->data->get_test('kdprogram','kdprogram');
foreach($result1 as $row1){
$array_temp[$index1] = $row1;
$result2 = $this->data->get_test('kdgiat','kdgiat','kdprogram = '.$row1['kdprogram']);
foreach($result2 as $row2){
$array_temp[$index1][$index2] = $row2;
$result3 = $this->data->get_test('kdoutput','kdoutput','kdprogram = '.$row1['kdprogram'].' and kdgiat = '.$row2['kdgiat']);
foreach($result3 as $row3){
$array_temp[$index1][$index2][$index3] = $row3;
$result4 = $this->data->get_test('kdsoutput','kdsoutput','kdprogram = '.$row1['kdprogram'].' and kdgiat = '.$row2['kdgiat'] .' and kdoutput = '.$row3['kdoutput']);
foreach($result4 as $row4){
$array_temp[$index1][$index2][$index3][$index4] = $row4;
$index4++;
}
$index3 ++;
}
$index2 ++;
}
$index1 ++;
}
//print_r($array_temp);
$data['damn'] = $array_temp;
$this->load->view('report/laporan_output', $data);
}
$data contains:
Array
(
[0] => Array
(
[kdprogram] => 06
[0] => Array
(
[kdgiat] => 3400
[0] => Array
(
[kdoutput] => 001
[0] => Array
(
[kdsoutput] => 001
)
[1] => Array
(
[kdsoutput] => 006
)
)
[1] => Array
(
[kdoutput] => 008
[2] => Array
(
[kdsoutput] => 001
)
)
)
)
)
How to echo each array (kdprogram, kdgiat, etc) on view especially with html table?
Am i doing it right?
Thanks
it looks kinda ugly and i would use some sort of recursive function but here is your way
in controller ( i assume the arrays have numeric index otherwise you have to use some sort of counter like you did in your code )
foreach($result1 as $a_counter=>$row1)
{
$array_temp[$a_counter] = array( 'parent'=>$row1 , 'child'=>array());
$result2 = $this->data->get_test('kdgiat','kdgiat','kdprogram = '.$row1['kdprogram']);
foreach($result2 as $b_counter=> $row2)
{
$array_temp[$a_counter]['child'][$b_counter] = array( 'parent'=>$row2 , 'child'=>array());
$result3 = $this->data->get_test('kdoutput','kdoutput','kdprogram = '.$row1['kdprogram'].' and kdgiat = '.$row2['kdgiat']);
foreach($result3 as $c_counter=>$row3)
{
$array_temp[$a_counter]['child'][$b_counter]['child'][$c_counter] = array( 'parent'=>$row3 , 'child'=>array());
$result4 = $this->data->get_test('kdsoutput','kdsoutput','kdprogram = '.$row1['kdprogram'].' and kdgiat = '.$row2['kdgiat'] .' and kdoutput = '.$row3['kdoutput']);
foreach($result4 as $row4)
{
$array_temp[$a_counter]['child'][$b_counter]['child'][$c_counter]['child'][] = $row;
}
}
}
}
in the view
foreach($result as $a )
{
// show a
foreach($a['child'] as $b )
{
// show b
foreach($b['child'] as $c )
{
// show c
foreach($c['child'] as $d )
{
// show d
}
}
}
}

How to split slash / separated string in two variable in php

Assume that applicant id was passed from the other form.I have array variable coming from my database, here is the code :
$array_id_applicants = explode(";",stripslashes($applicant_id1));
$applicants_num = count($array_id_applicants);
$arr_app_num = array();
for($x=0;$x<=$applicants_num;$x++)
{
if($array_id_applicants[$x]){
$applicant_id = str_replace("'","",$array_id_applicants[$x]);
$applicants = getdata("select cellphone from personal where applicant_id='".$applicant_id."'");
$replace_array = array("-","(",")","+","_");
array_push($arr_app_num,str_replace($replace_array,"",$applicants[1][cellphone]));
}
}
$applicant_number = implode(";",$arr_app_num);
echo $applicant_number; exit;
Assume that this is the value of array :
$applicant_number = '639152478931 / 631687515455','631235497891'
I want the output to be like this :
$applicant_number = '639152478931','631687515455','631235497891'
See if this is what you are trying to do.:
<?php
$applicant_number[] = '639152478931 / 631687515455';
$applicant_number[] = '631235497891';
$applicant_number[] = '0294765388389 / 52525252525';
$applicant_number[] = '0012324252728';
$new = array();
foreach($applicant_number as $number) {
if(strpos($number,'/') !== false) {
$val = explode("/",str_replace(" ","",$number));
$new = array_merge($new,$val);
}
else
$new[] = $number;
}
print_r($new);
?>
Gives you:
Array
(
[0] => 639152478931
[1] => 631687515455
[2] => 631235497891
[3] => 0294765388389
[4] => 52525252525
[5] => 0012324252728
)
<?php
$applicant_number[] = '639152478931';
$applicant_number[] = '631235497891';
$applicant_number[] = '1111111110294765388389';
$applicant_number[] = '0012324252728';
$new = array();
foreach($applicant_number as $number) {
$count = strlen($number) - 10;
$b = substr($number,$count);
$new[] = "+63".$b;
}
print_r($new);
?>
Gives you :
Array ( [0] => +639152478931 [1] => +631235497891 [2] => +634765388389 [3] => +632324252728 )

Breaking up a string into an array, PHP

I have a string that looks like this:
$dash_access = "1-10:rw,14:rw|10-10:ro,14:ro";
My goal, is to break this string up into an array. I think I'm close, but can't quite figure it out. I want my array structure to look like this:
$array = Array
(
[1] => Array
(
[10] => rw
[14] => rw
)
[10] => Array
(
[10] => ro
[14] => ro
)
)
This is what I have so far, but it's not working.
$dash_access_split = explode("|",$dash_access);
for ($a=0;$a<count($dash_access_split);$a++) {
$split1 = explode("-", $dash_access_split[$a]);
$split2 = explode(",", $split1[1]);
for ($b=0;$b<count($split2);$b++) {
$split3 = explode(":", $split2[$b]);
$dash_access_array[$split1[0]][] = $split3[0];
$dash_access_array[$split1[0]][] = $split3[1];
}
}
Think of it as crumbling a cookie. Break it into progressively smaller pieces and process each piece accordingly.
Something like this should work
$dashAccess = "1-10:rw,14:rw|10-10:ro,14:ro";
$outArray = [];
foreach (explode('|', $dashAccess) as $bigPiece) {
list($medKey, $medPiece) = explode('-', $bigPiece);
$outArray[$medKey] = [];
foreach (explode(',', $medPiece) as $smallPiece) {
list($crumbleKey, $crumblePiece) = explode(':', $smallPiece);
$outArray[$medKey][$crumbleKey] = $crumblePiece;
}
}
var_dump($outArray);
Here's a fiddle
<?php $dash_access = "1-10:rw,14:rw|10-10:ro,14:ro";
$big_array=explode('|',$dash_access);
$small_array=array();
foreach($big_array as $key=>$value)
{
$small_array[]=explode('-',$value);
foreach($small_array as $key => $value)
{
$chunk=explode(',',$value[1]);
foreach($chunk as $value1)
{
$chunk_small=explode(':',$value1);
$result[$value[0]][$chunk_small[0]]=$chunk_small[1];
}
}
}
print_r($result);
http://codepad.org/sKZyDu2m

Group data by multiple fields dynamically in PHP

I want to group an associative array by fields. The array itself is originally from a mysql database query.
Below is an example of how I do it by hard coding it:
<?php
$fields = array("ID,subID");
$fieldCounts = count($fields);
$data = array(); //there is sql querieed data
$parsedData = array();
foreach ($data as $val)
{
if ($fieldCounts == 1)
{
$f0 = $fields[0];
$fv0 = $val[$f0];
$parsedData[$fv0][] = $val;
}
else if ($fieldCounts == 2)
{
$f0 = $fields[0];
$fv0 = $val[$f0];
$f1 = $fields[10];
$fv1 = $val[$f1];
$parsedData[$fv0][$f1][] = $val;
}
else
{
exit("Third field not implemented");
}
}
?>
But how can I do it dynamically with an arbitrary number of fields?
Am not sure how this code has worked for you but some things are that wrong and might not allow the code to function properly
Fields has only as one valued with ,
$fields = array("ID,subID");
^----------- between string
Instead of
$fields = array("ID","subID");
Notice: Undefined offset:
$f1 = $fields[10];
^----- your array is not up to 10
Since you did not put your generate data and desired output. I would assume your final output and generate some temporary data
$fields = array("ID","subID"); //You can Increase or decrease this Fields
$fieldCounts = count($fields);
$data = array(); // there is sql querieed data
for($i = 0; $i < 3; $i ++) {
$data[] = array("ID" => mt_rand(1, 1000),"subID" => "sub" . mt_rand(100, 900));
}
Ruining your code with the 2 corrections above
foreach ( $data as $val ) {
if ($fieldCounts == 1) {
$f0 = $fields[0];
$fv0 = $val[$f0];
$parsedData[$fv0][] = $val;
} else if ($fieldCounts == 2) {
$f0 = $fields[0];
$fv0 = $val[$f0];
$f1 = $fields[1];
$fv1 = $val[$f1];
$parsedData[$fv0][$f1][] = $val;
} else {
exit("Third field not implemented");
}
}
Output
Array
(
[159] => Array
(
[subID] => Array <----------- SubID is fixed in your can cause confict
(
[0] => Array
(
[ID] => 159
[subID] => sub589
)
)
)
[334] => Array
(
[subID] => Array
(
[0] => Array
(
[ID] => 334
[subID] => sub703
)
)
)
)
A better Alternative to yours
$parsedData = array();
foreach ( $data as $val ) {
$temp = &$parsedData;
foreach ( array_slice($val, 0, $fieldCounts) as $key ) {
$temp = &$temp[$key];
}
$temp[] = $val;
}
print_r($parsedData);
Output
Array
(
[159] => Array
(
[sub589] => Array <---------- Make Sub ID Dynamic
(
[0] => Array
(
[ID] => 159
[subID] => sub589
)
)
)
[334] => Array
(
[sub703] => Array
(
[0] => Array
(
[ID] => 334
[subID] => sub703
)
)
)
)
Recommended Version For easy array path
$parsedData = array();
foreach ( $data as $val ) {
$temp = &$parsedData;
foreach ( array_slice($val, 0, $fieldCounts) as $key ) {
$temp = &$temp[$key];
}
$temp = $val;
}
print_r($parsedData);
Output
Array
(
[159] => Array
(
[sub589] => Array <---- Easy to asses as $parsedData['159']['sub589']
(
[ID] => 159
[subID] => sub589
)
)
[334] => Array
(
[sub703] => Array
(
[ID] => 334
[subID] => sub703
)
)
)
Instead of doing if/elseif/else inside your $data foreach-loop (which is always limited to the number you "write" in there with that structure and a lot of code-duplicateion) you need to turn that if/elseif/else into a loop of it's own.
But first of all transform the existing code, I start in the first if body, it contains already all code necessary:
$f0 = $fields[0];
$fv0 = $val[$f0];
$parsedData[$fv0][] = $val;
The $val should be assigned to the array $parsedData which is keyed by $fields name $value. Let's compress this here, the number 0 in names is superfluous as we don't want it any longer (but maybe the first):
$field = $fields[0];
$value = $values[$field];
$parsedData[$value][] = $values;
(I changed $val into $values to improve naming). This is now more easy to read and understand. Also we spot the magic number 0 here more easily.
Now to the magic. We want to add to an array here (push):
$parsedData[$value][] = $values;
To make this more easy, let's turn it this way:
$array = &$parsedData[$value];
$array[] = $values;
This right now seems superfluous, but when this turns into a loop, it will become more clear:
$array = &$parsedData;
...
$array = &array[$value];
...
$array[] = $values;
Let's review the code in with the outer loop at this moment:
foreach ($data as $values)
{
$array = &$parsedData;
$field = $fields[0];
$value = $values[$field];
$array = &$array[$value];
$array[] = $values;
}
Obviously this code is yet not complete. The inner-loop is missing but it starts to get some kind of body. And actually the inner loop is pretty simple to achieve:
$array = &$parsedData;
foreach ($fields as $field)
{
$value = $values[$field];
$array = &$array[$value];
}
$array[] = $values;
And that's already it. The single field has been turned into an iteration over all fields. The aliasing/referencing of the sub-array per each step in the iteration allows to push the value to the appropriate array entry after the inner loop has finished.
The whole outer and inner loop:
foreach ($data as $values)
{
$array = &$parsedData; # set reference
foreach ($fields as $field)
{
$value = $values[$field];
$array = &$array[$value];
}
$array[] = $values;
unset($array); # remove reference
}

Categories