PHP: array_splice() not giving me correct output - php

I'm trying to experiment with array_splice and I get an output like this (from $match)
Array
(
[Keep me Updated] => Array
(
[winner] => winnerl.jpg
[0] => value0.jpg
)
[0] => valuel.jpg //this should really be inside [Leep me Updated] array
[1] => value2.jpg //this should really be inside [Leep me Updated] array
[2] => value3.jpg //this should really be inside [Leep me Updated] array
}
from (this foreach creates puts in the values into $match)
foreach($data as $d)
{
if (isset($match[$d['data']['name']])) {
$match_loser = array($d['loser']['lrg_img']);
array_splice($match,1,0,$match_loser);
}else{
$match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
$d['loser']['lrg_img']);
}
}
What I'm trying to get is bring [0],[1],[2] into the [Keep me Updated] $match array:
Array
(
[Keep me Updated] => Array
(
[winner] => winnerl.jpg
[0] => value0.jpg
[1] => value1.jpg // old one: [0] => valuel.jpg
[2] => value2.jpg // old one: [1] => value2.jpg
[3] => value3.jpg // old one: [2] => value3.jpg
)
}
This is what $data looks like
$data[] = array(
"data"=>array
(
"name"=>$name,
),
"winner"=>array
(
"lrg_img"=>$img_url_winner
),
"loser"=>array
(
"lrg_img"=>$img_url_loser
)
$data has array values, and $match is where I'm trying to sort the data. So if my values match, it'll consolidate.
Thanks!

Use the inner array as the argument to array_splice
foreach($data as $d)
{
if (isset($match[$d['data']['name']])) {
$match_loser = array($d['loser']['lrg_img']);
array_splice($match[$d['data']['name']],1,0,$match_loser);
}else{
$match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
$d['loser']['lrg_img']);
}
}

Related

Replace every string in multidimensional array if conditions matched

Ok so I have an array look like this,
Array
(
[0] => Array
(
[0] => order_date.Year
[1] => =
[2] => 2024
),
[1] => Array
(
[0] => order_date.Quarter
[1] => =
[2] => 1
)
)
What I want to do is, in any element of this multidimensional array I want to replace any string that have a . with removing everything after .
So the new array should look like this,
Array
(
[0] => Array
(
[0] => order_date
[1] => =
[2] => 2024
),
[1] => Array
(
[0] => order_date
[1] => =
[2] => 1
)
)
I have tried doing this,
foreach ($filter as $key => $value) {
if(is_array($value)) {
$variable = substr($value[0], 0, strpos($value[0], "."));
$value[0] = $variable;
}
}
print_r($filter);
I'm getting $value[0] as order_date but can't figure out how to assign it to $filter array without affecting other values in array;
The $value variable is not linked with the original array in the foreach loop.
You can make a reference to the original array by using ampersand "&"
foreach ($filter as $key => &$value) { ... }
Or you can use old school key nesting
$filter[$key][0] = $variable;
Please take a look here https://stackoverflow.com/a/10121508/9429832
this will take off values after . in every element of any multidimensional array.
// $in is the source multidimensional array
array_walk_recursive ($in, function(&$item){
if (!is_array($item)) {
$item = preg_replace("/\..+$/", "", $item);
}
});

Creating and pushing to arrays

I am trying to create an array(if it does not already exist) and then push values to it.
foreach($playlist->items as $item) {
$str = $item->snippet->title;
$id = $item->snippet->resourceId->videoId;
$substring = substr($str, 0, 5);
$substring = strtolower($substring);
if (is_array($substring)) {
array_push($substring, $id);
}
else {
$substring = array();
array_push($substring, $id);
}
array_push($artists, $substring);
}
I am iterating through data retrieved from a Youtube playlist, so I go through each item with foreach which holds a 'title' - the artist and an 'id' - the video Id . I substring each title and try to use this to group artists into specific arrays.
If an array already exists for that artist, I try to push the 'id' onto the end of that array. If an array does not exist, I create one and then push the 'id' onto that array.
At the end I try to push each artist array into the 'artists' array.
What I get when I print out $artists array is something like this
Array
(
[0] => Array
(
[0] => 1_YUrdjLyAU
)
[1] => Array
(
[0] => Gp8lDW2LUM0
)
...
[543] => Array
(
[0] => Exa0CzlCb3Y
)
Every single $id is in it's own array when they should be grouped together based on $substring. e.g
Array
(
[0] => Array
(
[0] => 1_YUrdjLyAU
[1] => 1_YUrdjLyAU
[2] => 1_YUrdjLyAU
[3] => 1_YUrdjLyAU
[4] => 1_YUrdjLyAU
)
[1] => Array
(
[0] => Gp8lDW2LUM0
[1] => 1_YUrdjLyAU
[2] => 1_YUrdjLyAU
[3] => 1_YUrdjLyAU
)
What am I not understanding?
Here is a simpler solution to your problem:
$artists = array();
foreach($playlist->items as $item) {
$artist = $item->snippet->artist; // however the artist name is fetched..
$id = $item->snippet->resourceId->videoId;
$artists[$artist][] = $id
}
This way, you don't need to check if an artist is already in the array, it will do that automatically and append the video id to the artist.
The $artists array will be assosiative, I don't think you can do it with a numeric array.
The array will look like this:
Array
(
['Jon Lajoie'] => Array
(
[0] => 1_YUrdjLyAU
[1] => lf3hflkap39
[2] => 1vt1455zzbe
[3] => 6dthg3drgjb
[4] => jfop3ifjf3p
)
['Lonely Island'] => Array
(
[0] => Gp8lDW2LUM0
[1] => 5he5hj67j7r
[2] => krt7tkktzk8
[3] => we54w4ggsrg
)
)
Use substring as array key and do following:
**Remove**
if (is_array($substring)) {
array_push($substring, $id);
}
else {
$substring = array();
array_push($substring, $id);
}
array_push($artists, $substring);
**Replace**
$artist[$substring][]=$id;

multiDimensional Array need as

Actual array as below is basically the array of $_POST.
One can understand what is coming from the form. three controls with same name different value. What i need is below this array.
Array
(
[mytext] => Array
(
[0] => aaaa
[1] => bbbb
[2] => ddd
)
[mysel] => Array
(
[0] => one
[1] => two
[2] => two
)
[submit] => Submit
)
I need the array in row format below but be dynamic based of $_POST data.
Array
(
[0] => Array
(
[0] => aaaa
[1] => one
)
[1] => Array
(
[0] => bbbb
[1] => two
)
[2] => Array
(
[0] => dddd
[1] => two
)
)
Try this:
$out = Array();
foreach($_POST['mytext'] as $k=>$v) {
$out[$k] = Array($v,$_POST['mysel'][$k]);
}
var_dump($out);
// Code To Get controls value in row wise
$count=0;
foreach($_POST as $key=>$val){
foreach($_POST[$key] as $val2){
$row[$count][]=$val2;
$count++;
}
$count=0;
}
print_r($row);
Loop through one of the fields, and then pull the corresponding value from the other field.
$result = array();
foreach($_POST['mytext'] as $k=>$v){
$result[] = array($v, $_POST['mysel'][$k]);
}
You can also use array_map to do this:
// PHP 5.3+
$result = array_map(function($a, $b){
return array($a, $b);
}, $_POST['mytext'], $_POST['mysel']);
// PHP <= 5.2
$result = array_map(create_function('$a,$b', 'return array($a,$b);'), $_POST['mytext'], $_POST['mysel']);

PHP Group array by values

I have an array like this:
Array (
[0] => ing_1_ing
[1] => ing_1_amount
[2] => ing_1_det
[3] => ing_1_meas
[4] => ing_2_ing
[5] => ing_2_amount
[6] => ing_2_det
[7] => ing_2_meas
)
And I want to group the values into an array like this:
Array (
[0] => Array(
[0] => ing_1_ing
[1] => ing_1_amount
[2] => ing_1_det
[3] => ing_1_meas
)
[1] => Array(
[0] => ing_2_ing
[1] => ing_2_amount
[2] => ing_2_det
[3] => ing_2_meas
)
)
There may be many other items named like that: ing_NUMBER_type
How do I group the first array to the way I want it? I tried this, but for some reason, strpos() sometimes fails:
$i = 1;
foreach ($firstArray as $t) {
if (strpos($t, (string)$i)) {
$secondArray[--$i][] = $t;
} else {
$i++;
}
}
What is wrong? Can you advice?
It depends what you are trying to achieve, if you want to split array by chunks use array_chunk method and if you are trying to create multidimensional array based on number you can use sscanf method in your loop to parse values:
$result = array();
foreach ($firstArray as $value)
{
$n = sscanf($value, 'ing_%d_%s', $id, $string);
if ($n > 1)
{
$result[$id][] = $value;
}
}
<?php
$ary1 = array("ing_1_ing","ing_1_amount","ing_1_det","ing_1_meas","ing_2_ing","ing_2_amount","ing_2_det","ing_2_meas");
foreach($ary1 as $val)
{
$parts = explode("_",$val);
$ary2[$parts[1]][]=$val;
}
?>
This creates:
Array
(
[1] => Array
(
[0] => ing_1_ing
[1] => ing_1_amount
[2] => ing_1_det
[3] => ing_1_meas
)
[2] => Array
(
[0] => ing_2_ing
[1] => ing_2_amount
[2] => ing_2_det
[3] => ing_2_meas
)
)
What I'd do is something like this:
$result = array();
foreach ($firstArray as $value)
{
preg_match('/^ing_(\d+)_/', $value, $matches);
$number = $matches[1];
if (!array_key_exists($number, $result))
$result[$number] = array();
$result[$number][] = $value;
}
Basically you iterate through your first array, see what number is there, and put it in the right location in your final array.
EDIT. If you know you'll always have the numbers start from 1, you can replace $number = $matches[1]; for $number = $matches[1] - 1;, this way you'll get exactly the same result you posted as your example.

How can I create multidimensional arrays from a string in PHP?

So My problem is:
I want to create nested array from string as reference.
My String is "res[0]['links'][0]"
So I want to create array $res['0']['links']['0']
I tried:
$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');
when print_r($res)
I see:
<b>Notice</b>: Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>
I need to see:
Array
(
[0] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[class] => 3
)
)
)
[1] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 3
[class] => 9
)
)
)
)
Thanks for any help.
So you have a description of an array structure, and something to fill it with. That's doable with something like:
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
// unoptimized, always uses strings
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );
Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:
array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);
Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.
I have a very stupid way for this, you can try this :-)
Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example
$tmp = '$'.'res[0]['links'][0]'.'= array()';
eval($tmp);
Now you can use your array $res
100% work around and :-)
`
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');
print_r($res);
but read the comments first and learn about arrays first.
In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:
[2] => Array
(
[name] => apple[color]
[value] => red
)
[3] => Array
(
[name] => appleSeeds[27][genome]
[value] => 201
)
[4] => Array
(
[name] => appleSeeds[27][age]
[value] => 2 weeks
)
[5] => Array
(
[name] => apple[age]
[value] => 3 weeks
)
[6] => Array
(
[name] => appleSeeds[29][genome]
[value] => 103
)
[7] => Array
(
[name] => appleSeeds[29][age]
[value] => 2.2 weeks
)
into
Array
(
[apple] => Array
(
[color] => red
[age] => 3 weeks
)
[appleSeeds] => Array
(
[27] => Array
(
[genome] => 201
[age] => 2 weeks
)
[29] => Array
(
[genome] => 103
[age] => 2.2 weeks
)
)
)
This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:
function MergeArrays($Arr1, $Arr2) {
foreach($Arr2 as $key => $Value) {
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else { $Arr1[$key] = $Value; }
}
return $Arr1;
}
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
$sub = array();
array_create($sub, $v['name'], $v['value']);
$result = MergeArrays($result, $sub);
}

Categories