Jump to content

unset subject of foreach loop


Inigo

Recommended Posts

Hi guys,

 

I wonder if anyone could help me. I have a string of data pertaining to images that is being passed from an ajax function. It is full of ID:VALUE pairs like this-

 

title1:something,caption1:blah blah blah,align1:left,width1:100,height1:100,title2:something else,caption2:more blah blah,align2:right,width2:300,height2:100

 

etc. (The digit after each id relates to the image- a crude way of data stuffing..) I've exploded this string by means of the comma separator into the $field_values array, so that it's now arranged like this-

$field_values[0] = 'title1:something'

$field_values[1] = 'caption1:blah blah blah'

$field_values[2] = 'align1:left'

 

...etc. With me so far? Right, so now I'm going to extract the id and value from each pair and put it into a new array of $image_data, where the first array key of $image_data is the no. of the image..like this-

 

 

foreach($field_values as $pair){

if(substr($pair['id'], -1) == '1'){

$field_id = substr($pair['id'],0,-1);

$image_data[1][$field_id] = $pair['value'];

}

}

 

... And then I'd do the same for all the id:value pairs for image no.2.

 

HOWEVER... I'd like to speed things up so that when I'm searching the $field_values array for the 2nd and 3rd image ID:VALUE pairs, it's not wasting time by cycling through all the pairs that I've already identified and put into the $image_data array. I thought I could use unset(), but I'm not sure quite how to implement it here.

 

I hope that my question is intelligible, and that somebody might be able to help me..?

 

 

Many Thanks!

 

Link to comment
https://forums.phpfreaks.com/topic/219309-unset-subject-of-foreach-loop/
Share on other sites

if i understand correctly, this might work for you.

 

foreach ($field_values as $pair) {
// Break the $pair into lable/value
$pair_parts = explode(':', $pair);

// Get the text value and number value from the left side
$field_id = preg_replace("/[\d]/","",$pair_parts[0]); // all letters
$img_id = preg_replace("/[\D]/","",$pair_parts[0]); // all numbers

$image_data[$img_id][$field_id] = $pair_parts[1];
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.